autofac - 正在解决错误的键控服务

时间:2016-07-08 03:59:41

标签: c# .net autofac

我正在使用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

我做错了什么?

1 个答案:

答案 0 :(得分:0)