![](/img/trans.png)
[英]How to pass in settings into a class (derived ASP.NET Core Startup.cs) from ConfigureServices in a test
[英]How to pass connection string to UnitOfWork project from startup.cs asp.net core
我在AppDbContext
创建了构造函数,并且上下文是在UnitofWork
中实现的,该实现将字符串传递给上下文,但是当我注册unitofwork
时如何将连接字符串传递给startup.cs 。 Repository
和UnitOfWork
在不同的项目中
以下是我的代码,
构造函数的连接字符串
private readonly string _connection;
public AppDbContext(string connection)
{
_connection=connection;
}
UnitOfWork构造函数
public UnitOfWork(string connection)
{
_context = new AppDbContext(connection);
}
在StartUp.cs中 ,我可以通过下面的连接字符串,从appsettings.json中读取吗?
services.AddTransient<IUnitOfWork, UnitOfWork>();
不要那样做 如果已经使用DI,则将上下文注入UOW并在启动期间配置上下文。
public class UnitOfWork : IUnitOfWork {
private readonly AppDbContext _context;
public UnitOfWork(AppDbContext context) {
_context = context;
}
//...other code removed for brevity
}
并使用以下示例创建数据库上下文。
public class AppDbContext : DbContext {
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {
}
//...other code removed for brevity
}
然后,使用依赖项注入来注册包括上下文在内的所有内容
public void ConfigureServices(IServiceCollection services) {
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddTransient<IUnitOfWork, UnitOfWork>();
services.AddMvc();
}
配置从appsettings.json文件中读取连接字符串。
{
"ConnectionStrings": {
"DefaultConnection": "connection string here"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.