4

我正在使用 Autofac。我想根据应用于构造函数参数的属性注入不同的依赖项实现。例如:

class CustomerRepository
{
    public CustomerRepository([CustomerDB] IObjectContainer db) { ... }
}

class FooRepository
{
    public FooRepository([FooDB] IObjectContainer db) { ... }
}

builder.Register(c => /* return different instance based on attribute on the parameter */)
       .As<IObjectContainer>();

属性将提供数据,例如连接字符串,我可以用它来实例化正确的对象。

我怎样才能做到这一点?

4

2 回答 2

9

听起来您想提供IObjectContainertoCustomerRepository和的不同实现FooRepository。如果是这样的话,属性可能是一把薄金属尺子。相反,我将向您展示如何使用 Autofac 实现多个实现。

.ContainerScoped()(为简洁起见,省略了诸如此类的电话。)

首先,IObjectContainer通过命名注册为每个连接字符串注册一个版本:

builder
    .Register(c => new ObjectContainer(ConnectionStrings.CustomerDB))
    .As<IObjectContainer>()
    .Named("CustomerObjectContainer");

builder
    .Register(c => new ObjectContainer(ConnectionStrings.FooDB))
    .As<IObjectContainer>()
    .Named("FooObjectContainer");

然后,解析存储库注册中的特定实例:

builder.Register(c => new CustomerRepository(
    c.Resolve<IObjectContainer>("CustomerObjectContainer"));

builder.Register(c => new FooRepository(
    c.Resolve<IObjectContainer>("FooObjectContainer"));

这使存储库没有配置信息:

class CustomerRepository
{
    public CustomerRepository(IObjectContainer db) { ... }
}

class FooRepository
{
    public FooRepository(IObjectContainer db) { ... }
}
于 2010-03-21T04:50:07.407 回答
0

Bryan's answer is good enough while you have several repositories and they have few constructor parameters. But it is difficult to set up your root when you have many of them. You can achieve this by scanning your class metadata on resolving an interface. When you get info about its parameters you can resolve actual implementation of it. See my answer here.

于 2013-09-28T12:55:30.990 回答