2017-08-09 28 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());

我希望它可以幫助你,

胡安