2016-07-08 48 views
1

我使用autofac並嘗試pick a service implementation by context。基本思想是有兩個存儲庫 - 一個連接到數據庫Db1,另一個連接到數據庫Db2。我試圖使用鍵控服務來指示需要哪個數據庫連接。autofac - 錯誤的鍵控服務正在解決中

下面的代碼:

public class Db1Repository(IDbConnection dbConnection) 
{ 
    // ... 
} 

public class Db2Repository(IDbConnection dbConnection) 
{ 
    // ... 
} 

public class ClassThatDoesSomethingSpecial(Db1Repository repository) 
{ 
    // ... 
} 

var builder = new ContainerBuilder(); 

builder.RegisterType<SqlConnection>() 
     .WithParameter("connectionString",ConfigurationManager.ConnectionStrings["Db1"].ConnectionString) 
     .As<IDbConnection>() 
     .Keyed<IDbConnection>("Db1"); 

builder.RegisterType<SqlConnection>() 
     .As<IDbConnection>() 
     .WithParameter("connectionString", ConfigurationManager.ConnectionStrings["Db2"].ConnectionString) 
     .Keyed<IDbConnection>("Db2"); 

builder.RegisterType<Db1Repository>() 
     .WithParameter(
      new ResolvedParameter(
       (pi, ctx) => pi.ParameterType == typeof(IDbConnection), 
       (pi, ctx) => ctx.ResolveKeyed<IDbConnection>("Db1") 
      ) 
     ); 

builder.RegisterType<ClassThatDoesSomethingSpecial>(); 

var container = builder.Build(); 

var myclass = container.Resolve<ClassThatDoesSomethingSpecial>(); 

應該發生什麼: 被注入的ClassThatDoesSomethingSpecial構造函數的Db1Repository應該有一個IDbConnection這是解析爲SqlConnectionDB1

相反,IDbConnection解析爲SqlConnectionDb2

我在做什麼錯?

+0

會發生什麼事,如果你使用'名爲<的IDbConnection>( 「DB1」)'而不是爲每個連接註冊的? – Amy

+0

@Amy - 同樣的問題。 – MCS

+1

我試過你的代碼,一切都按預期工作:https://dotnetfiddle.net/PLE3Uz –

回答

0

試試這個:

builder 
    .RegisterType<Db1Repository>() 
    .WithParameter(ResolvedParameter.ForNamed<IDbConnection>("Db1")); 

https://autofac.org/apidoc/html/CF9E2168.htm

+0

同樣的問題:( – MCS

+1

哇,好吧,我會留下答案,所以其他人也不會建議這:( – Amy

相關問題