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)?
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")
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With