ASP.NET Core DI in a class library?

There is no difference between controller and class from a class library. You need to

  1. Define a class in a class library and inject IDatabaseConnectionString into it. Your UserFactory is the right way.

  2. register the UserFactory for DI

    serviceCollection.AddScoped<IUserFactory, UserFactory>();
    
  3. Resolve the UserFactory by the DI. For example, use the UserFactory as the constructor parameter in some controller. Everything is connected by DI automatically.

    public MyController(IUserFactory userFactory)
    {
        _userFactory = myUserFactory;
    }
    

Here is the good explanation for understanding Composition root.


I know that I can add the IDatabaseConnectionString to a constructor of a controller in ASP.NET to get the container.

No, that's not needed and it would be wrong.

just adding the IDatabaseConnectionString to the constructor of a class in the class library do not work.

It doesn't work because you need to create the service that will use the connection string and add it to the services container.

For example:

public class Repository: IRepository
{
    public Repository(IDatabaseConnectionString databaseConnectionString)
    {
        _databaseConnectionString = databaseConnectionString;
    }
}

public class ServiceThatRequiresDatabase : IServiceThatRequiresDatabase
{
    public ServiceThatRequiresDatabase(IRepository repository)
    {
        _repository = repository;
    }
}

// ...
services.AddScoped<IRepository, Repository>();
services.AddScoped<IServiceThatRequiresDatabase, ServiceThatRequiresDatabase>();


public class HomeController : Controller
{
    public HomeController(IServiceThatRequiresDatabase service)
    {
        _service = service;
    }
}

By the way, as @YeldarKurmangaliyev said, your DatabaseConnectionString should be like this if you want to make it read-only:

public class DatabaseConnectionString : IDatabaseConnectionString
{
    public string ConnectionString { get; }

    public DatabaseConnectionString(string connectionString)
    {
        ConnectionString = connectionString;
    }
}