如何从startup.cs asp.net核心传递连接字符串到UnitOfWork项目

Roh*_*hit 2 c# entity-framework-core .net-core asp.net-core

我创建了构造函数AppDbContext和上下文实现,UnitofWork其中将字符串传递给上下文但是当我注册时如何将连接字符串传递给startup.csunitofwork.Repository并且UnitOfWork在不同的项目中

以下是我的代码,

连接字符串到构造函数

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

    _connection=connection;

}
Run Code Online (Sandbox Code Playgroud)

UnitOfWork构造函数

public UnitOfWork(string connection)
{
    _context =  new AppDbContext(connection);
}
Run Code Online (Sandbox Code Playgroud)

StartUp.cs中,我可以传递下面的连接字符串,从appsettings.json读取吗?

 services.AddTransient<IUnitOfWork, UnitOfWork>();
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 5

不要那样做.如果已经使用DI,则将上下文注入UOW并在启动期间配置上下文.

public class UnitOfWork : IUnitOfWork {
    private readonly AppDbContext _context;
    public UnitOfWork(AppDbContext context) {
        _context =  context;
    }

    //...other code removed for brevity
}
Run Code Online (Sandbox Code Playgroud)

并使用以下示例创建数据库上下文.

public class AppDbContext : DbContext {
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)  {
    }

    //...other code removed for brevity
}
Run Code Online (Sandbox Code Playgroud)

然后注册所有内容,包括依赖注入的上下文

public void ConfigureServices(IServiceCollection services) {

    services.AddDbContext<AppDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddTransient<IUnitOfWork, UnitOfWork>();

    services.AddMvc();
}
Run Code Online (Sandbox Code Playgroud)

配置从appsettings.json文件中读取连接字符串.

{
  "ConnectionStrings": {
    "DefaultConnection": "connection string here"
  }

}
Run Code Online (Sandbox Code Playgroud)