Asp.net-core – Dependency Injection in .NET Core inside a class library

.net coreasp.net-coreclass-librarydependency-injection

How can I inject one class into another inside a .NET Core library project?
Where should I configure DI as it is done in StartUp Class ConfigureServices in API project?

Best Answer

After googling a lot I could not find a comprehensive answer with an example to this question. Here is what should be done to use DI in Class library.

In your library:

public class TestService : ITestService
{
    private readonly ITestManager _testManager;

    public TestService(ITestManager testManager)
    {
        _testManager = testManager;
    }
}

public class TestManager : ITestManager 
{
    private readonly ITestManager _testManager;

    public TestManager()
    {
    }
}

Then extend IServiceCollection in the library:

public static class ServiceCollectionExtensions
{
    public static void AddTest(this IServiceCollection services)
    {
        services.AddScoped<ITestManager, TestManager>();
        services.AddScoped<ITestService, TestService>();
    }
}

Lastly in the main app StartUp (API, Console, etc):

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTest();
    }