Search code examples
c#dependency-injection.net-corenunitioc-container

.NET Core container definition for NUnit test project


I am quite new to .NET Core. How can I define a DI container within the NUnit class library project?

I know that it is done through IServiceCollection, but since there isn't any Startup method, I don't know where to get the instance implementing this interface.

Also I would like to be able to load definitions from other class libraries (being the subject of testing). That should be simpler as I can just create a static method in that class library with one parameter that is IServiceCollection, but again, how do I get it?

A side question is: I presume some of the interfaces could be mocked for the purpose of tests, but how can I replace a mapping already created using of of IServiceCollection's methods like AddSingleton or AddTransient?

There is a Remove method, but it is not documented.


Solution

  • IServiceCollection is implemented by the ServiceCollecion class. So if you want to do this for integration tests then you can use the ServiceCollection class to create your own ServiceProvider.

    var services = new ServiceCollection();
    
    services.AddTransient<IMyInterface, MyClass>();
    services.AddScoped<IMyScopedInteface, MyScopedClass>();
    ...
    
    var serviceProvider = sc.BuildServiceProvider();
    

    You can now use the serviceProvider instance in your tests to get your classes:

    var myClass = serviceProvider.GetService<IMyInterface>();
    

    If you want to mock some of the interfaces instead of using the real ones then, instead of adding the real class/interface into the service collection you can add a mock instead:

    mockInterface = new Mock<IMyInterface>();
    
    sc.AddScoped<IMyInterface>(factory => mockInterface.Object);