如何将连接字符串从启动.cs asp.net 核心传递到工作单元项目



>我在AppDbContext中创建了构造函数,上下文是在将字符串传递给上下文的UnitofWork中实现的,但是当我注册unitofwork时,如何在启动时将连接字符串传递给.cs.RepositoryUnitOfWork在不同的项目中

以下是我的代码,

构造函数的连接字符串

private readonly string _connection;
public AppDbContext(string connection) 
{
_connection=connection;
}

构造函数

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"
}
}

最新更新