c# - 如何将连接字符串从startup.cs asp.net core传递到UnitOfWork项目

标签 c# asp.net-core .net-core entity-framework-core

我在AppDbContext中创建了构造函数,并且上下文在UnitofWork中实现,它将字符串传递给上下文,但如何将连接字符串传递给startup.cs 当我注册 unitofwork 时。 RepositoryUnitOfWork 位于不同的项目

以下是我的代码,

构造函数的连接字符串

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,则将上下文注入(inject) 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
}

然后,您可以通过依赖注入(inject)注册所有内容,包括上下文

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

}

关于c# - 如何将连接字符串从startup.cs asp.net core传递到UnitOfWork项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45535311/

相关文章:

c# - IDocumentClient.UpsertDocumentAsync 不更新,它插入重复的 id

c# - 在 .NET Core 2 linux 守护进程中优雅地关闭通用主机

c# - 如何仅通过 Visual Studio 运行构建后构建事件

asp.net - .Net 核心路由 URLEncoded URL 不工作

mysql - Pomelo MySQL (.NET Core) 数据库故障后无法恢复

javascript - .Net Core 使用注销链接而不是按钮防止跨域 GET 请求

c# - 复制内部发布的树后,Docker镜像中缺少DLL

c# - 来自另一个表单的方法调用

javascript - 将 'Select All' 添加到 Bootstrap 多选表单/列表

Python 中的 C# BitConverter.ToSingle 等价物