我正在使用autofac并尝试pick a service implementation by context。基本思想是有两个存储库 - 一个连接到数据库Db1,另一个连接到数据库Db2。我正在尝试使用键控服务来指示需要哪个数据库连接。
以下是代码:
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>();
应该怎么做:
注入Db1Repository
构造函数的ClassThatDoesSomethingSpecial
应该有一个IDbConnection
已解析为SqlConnection
到 Db1 。
相反,IDbConnection
已解析为SqlConnection
到 Db2 !
我做错了什么?