Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 541
Nikishkin Sergey Avatar asked Mar 11 '23 18:03

Nikishkin Sergey


2 Answers

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")
like image 79
krontogiannis Avatar answered Mar 19 '23 03:03

krontogiannis


You can also use AddInstance method:

var connectionString=Configuration.GetConnectionString("DefaultConnection");
services.AddInstance<IRepository>(new Repository(connectionString));

But I'm agree with @MikeSW what he said in his comment above. You should register your DbContext and use it as parameter in your repository constructor:

 services.AddDbContext<AppDBContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

And your constructor would be:

public Repository(AppDBContext context)
{
    _appDBContext = context;
}
like image 43
octavioccl Avatar answered Mar 19 '23 01:03

octavioccl