C#-Autofac-使用多种实现

使用Autofac,我正在用一种类型注册2个实现.并且需要按需交换实现.但是它总是采用一种实现.

public class DataAccesss
{
    public IDatabaseHelper { get; set; }
}

Autofac

builder.RegisterType<DatabaseHelper>()
       .Named<IDatabaseHelper>("Sql")
       .WithParameter(new TypedParameter(IDatabaseHelper), new DatabaseHelper(new SqlFactory))
       .PropertiesAutowired();

builder.RegisterType<DatabaseHelper>()
       .Named<IDatabaseHelper>("Oledb")
       .WithParameter(new TypedParameter(IDatabaseHelper), new DatabaseHelper(new OleDbFactory))
       .PropertiesAutowired();

在控制器中,需要有这样的东西

1st - need to access `IDatabaseHelper` with `OleDb`
2nd - need to access  `IDatabaseHelper` with `Sql`

但是我的问题是IDatabaseHelper为null或始终使用OleDb而不是Sql.

解决方法:

当您解析单个组件时,Autofac将返回与该操作匹配的最新注册组件.

如果您需要在实现中访问这两个服务,则可以依赖IEnumerable< IDatabaseHelper>.它将解析所有IDatabaseHelper注册的服务.

另一种解决方案是依靠IIndex< TKey,TValue>.并命名注册

public class XController 
{
    public XController(IIndex<String, IDatabaseHelper> databaseHelpers) 
    {
        this._databaseHelpers = databaseHelpers; 
    }

    private readonly IIndex<String, IDatabaseHelper> _databaseHelpers;

    public void Do()
    {
        IDatabaseHelper oledb = this._databaseHelpers["Oledb"];
    }
}

您的注册将类似于:

builder.Register(c => new DatabaseHelper(new SqlFactory()))
       .Named<IDatabaseHelper>("Sql")
       .PropertiesAutowired();

builder.Register(c => new DatabaseHelper(new OleDbFactory()))
       .Named<IDatabaseHelper>("Oledb")
       .PropertiesAutowired();

有关更多信息,请参见Autofac文档中的Named and Keyed service.

上一篇:c#-Autofac有序列表作为参数


下一篇:c#-单元测试的Moq服务定位器