skip to Main Content

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.

2

Answers


  1. No, there isn’t any way to prevent this.

    I don’t really see it as a problem – if the user wants to sabotage how a library works, similar misconfigurations of IoC are equally possible for most other libraries.

    Login or Signup to reply.
  2. I also do not understand where the problem lies, let me break it down to smaller considerations:

    You use the interface and its implementation internally

    So, you have places where you use IOurService and injecting something else might break things (although such practice is used for "extension points, like in ASP.NET).

    To solve that, you should then stick to what you had – use concrete type instead to prevent "random injections of custom implementations". Or, if you want to keep interface, create another one internal interface IOurServiceInternal : IOurService, and register it and use it instead in your library.

    The consumer use the interface in their own code (quite obvious 😛 )

    Then the consumer speicfically writes in their code IOurService and expects it to work out of the box. This is only accomplished when you use your extension method to register the interface AddOurServices.

    But, if the customer implements IOurService interface AND also overrides DI registration – IMO this is extremely intentional and the consumer REALLY WANTS to inject his own implementation (although, this would make using your library unreasonable). So I would not worry much about this case as well.

    So, in turn, I would not overthink this and what you have is good.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search