使用基于构造函数参数属性的 autofac 解决依赖关系 [英] Resolve dependency with autofac based on constructor parameter attribute

查看:32
本文介绍了使用基于构造函数参数属性的 autofac 解决依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Autofac. I want to inject a different implementation of a dependency based on an attribute I apply to the constructor parameter. For example:

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>();

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

The attributes will be providing data, such as a connection string, which I can use to instance the correct object.

我该怎么做?

推荐答案

听起来你想提供 IObjectContainerCustomerRepositoryFooRepository<的不同实现/代码>.如果是这种情况,则属性可能是 细金属尺.相反,我将向您展示如何使用 Autofac 实现多个实现.

It sounds like you want to provide different implementations of IObjectContainer to CustomerRepository and FooRepository. If that is the case, attributes might be a thin metal ruler. Instead, I'll show you how I would implement multiple implementations with Autofac.

(为简洁起见,省略了诸如 .ContainerScoped() 之类的调用.)

(Calls such as .ContainerScoped() have been left out for brevity.)

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

First, register a version of IObjectContainer for each connection string by naming the registrations:

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

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

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

Then, resolve the specific instances in the repository registrations:

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

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

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

This leaves the repositories free of configuration information:

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

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

这篇关于使用基于构造函数参数属性的 autofac 解决依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆