2017-08-09 58 views
0

在我的任务(dotnet core,c#)中,有必要选择其中一个数据库并根据查询进行某种操作。dotnet muli db context

与微软的文档根据,它的样子:

public class db1 : DbContext, Idb 
{ 
    public db1(DbContextOptions options) : base(options) 
    {} 
} 

public class db2 : DbContext, Idb 
{ 
    public db2(DbContextOptions options) : base(options) 
    {} 
} 

在Startup.cs

services.AddDbContext<db1>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("db1"))); 

services.AddDbContext<db2>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("db2"))); 

这可以让你在DI注册和访问特定的数据库连接实例,但所有的数据库都硬编码。这是一个糟糕的代码。如何通过数据库的ID在DI中进行注册并通过控制器中的该ID选择DI的服务?

回答

0

它并没有那么糟糕,因为你可以根据你的环境改变连接字符串,让您的appsetings.json的不同版本(appsettings.dev.json,appsettings.release.json等等等等)

您在您的控制器contructors coulduse这些情境另一方面,即 构造函数1:

public FirstController(db1 context) 

ctor2:

public SecondController(db2 context) 

也许,ALSE,ctor3:

public ThirdController(db1 contextA, db2 contextB) 

但是:

一)考虑命名约定(IDB? db1 ??)

b)为什么你想拥有两个相同类型的存储库......哦!你想要有一个通用的存储库模式?那么你的答案就在这里:https://github.com/Arch/UnitOfWork(IM使用它,我非常hapy,结果和表现,我会贴一个例子波纹管)

使用IUnitOfWork:

在你的控制器:

 public YourController(IUnitOfWork unitOfWork) 
     { 
      try 
      { 
       _unitOfWork = unitOfWork; 
       // seeding 
       var ItemRepository = _unitOfWork.GetRepository<Item>(); 

//ETC... 

在启动,在ConfigureServices,调用此方法:

private void AddEntityFrameworkAndDbContext(IServiceCollection services) 
{ 
    services.AddEntityFrameworkSqlServer(); 
    var migrationsAssemblyName = typeof(YourContext).GetTypeInfo().Assembly.GetName().Name; 
    services.AddDbContext<YourContext>(options => 
    { 
     options.UseSqlServer(Your.ConnectionString.NoMAtterHowYouGetIt, 
      sqlServerOptionsAction: sqlOptions => 
      { 
       sqlOptions.MigrationsAssembly(migrationsAssemblyName); 
       sqlOptions.EnableRetryOnFailure(maxRetryCount: 5, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); 
      }); // Man, this is for free, I spent days getting it to work 
    }, 
    ServiceLifetime.Scoped // Showing explicitly that the DbContext is shared across the HTTP request scope (graph of objects started in the HTTP request) 
    ).AddUnitOfWork<YourContext>(); 
} 

而且在配置尝试类似:

app.EnsurePopulated(app.ApplicationServices.GetRequiredService());

我希望它可以帮助你,

胡安