I created constructor in AppDbContext
and context is implement in UnitofWork
which pass string to context but how can I pass connection string to at startup.cs when I register unitofwork
. Repository
and UnitOfWork
are in different project
Following is my code,
connection string to constructor
private readonly string _connection;
public AppDbContext(string connection)
{
_connection=connection;
}
UnitOfWork constructor
public UnitOfWork(string connection)
{
_context = new AppDbContext(connection);
}
in StartUp.cs , can I pass the connection string below, reading from appsettings.json ?
services.AddTransient<IUnitOfWork, UnitOfWork>();
Don't do that. If already using DI then inject the context into the UOW and configure the context during startup.
public class UnitOfWork : IUnitOfWork {
private readonly AppDbContext _context;
public UnitOfWork(AppDbContext context) {
_context = context;
}
//...other code removed for brevity
}
And create the database context using the following example.
public class AppDbContext : DbContext {
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {
}
//...other code removed for brevity
}
You then register everything including the context with dependency injection
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddMvc();
}
configuration reads the connection string from the appsettings.json file.
{
"ConnectionStrings": {
"DefaultConnection": "connection string here"
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.