We develop a NuGet package that customer can use add to their ASP.NET site.
public interface IOurService {
void DoStuff();
}
public class OurService: IOurService {
public void DoStuff() {
//do things here
}
}
Then we have a method to register our services in DI
public static void AddOurServices(this IServiceCollection services) {
services.AddSingleton<IOurService, OurService>();
}
The reason we have the interface IOurService
is that customer wants to mock the service in their unit tests, if the service is locked down, they are saying that testing is difficult.
However, the problem is that they can override IOurService
with their own implementation through DI.
services.AddOurSerivces();
services.AddSingleton<IOurService, TheirImplementation>();
Since we need the interface so the service can be mocked, we need to keep the interface and make it public. However, is there any practice to prevent clients from replacing our implementation through DI? If they do so and it does not work or introduce bugs, they will create support cases and we have to deal with that. It would be nice if we can prevent them from breaking the library in the first place.
You might try whether:
public abstract class OurService
{
internal OurService() {}
// polymorphic methods here
}
internal sealed class OurServiceImpl : OurService
{
// overrides here
}
does what you want, where OurService
replaces the interface and OurServiceImpl
is the type added by your registration code. Most mocking frameworks are perfectly capable of working past accessibility rules (the internal
constructor), but this would be inconvenient to most regular code. OurServiceImpl
would either be in the same assembly, or in an assembly nominated via [InternalsVisibleTo]
.
Important: "inconvenient" is not the same as "impossible". A sufficiently motivated actor can still bypass this via ref-emit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With