Search code examples
c#asp.net-corecode-injection

ASP.NET Core Dependency Injection


In my asp.net core solution I have 2 projects: asp.net app and library with model layer which contains pattern repository.

I ask DI in app realize my interface

services.AddTransient<IRepositrory, Repository>();

But! Repository constructor has parameter

public Repository(string connectionString)
{
    _appDBContext = new AppDBContext(connectionString);
}

How correctly configure DI to create repository with specific string from appsettings.json (asp.net app)?


Solution

  • There is an overload that accepts an implementation factory

    services.AddTransient<IRepository>(isp => new Repository(conn));
    

    You can get the connection string using

    Configuration.GetConnectionString("DefaultConnection")