使用Unity我怎么注入一个名为依赖成一个构造? [英] With Unity how do I inject a named dependency into a constructor?

查看:134
本文介绍了使用Unity我怎么注入一个名为依赖成一个构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有IRespository在以下code注册了两次(含名称):

I have the IRespository registered twice (with names) in the following code:

// Setup the Client Repository
IOC.Container.RegisterType<ClientEntities>(new InjectionConstructor());
IOC.Container.RegisterType<IRepository, GenericRepository>
    ("Client", new InjectionConstructor(typeof(ClientEntities)));

// Setup the Customer Repository
IOC.Container.RegisterType<CustomerEntities>(new InjectionConstructor());
IOC.Container.RegisterType<IRepository, GenericRepository>
    ("Customer", new InjectionConstructor(typeof(CustomerEntities)));

IOC.Container.RegisterType<IClientModel, ClientModel>();
IOC.Container.RegisterType<ICustomerModel, CustomerModel>();

但后来,当我想解决这个(使用IRepository)我必须做手工的决心是这样的:

But then when I want to resolve this (to use the IRepository) I have to do a manual resolve like this:

public ClientModel(IUnityContainer container)
{
   this.dataAccess = container.Resolve<IRepository>(Client);

   .....
}

我想这样做是有它在构造函数中(就像IUnityContainer)解决。我需要一些方法说哪个命名类型解析到。

What I would like to do is to have it resolved in the constructor (just like IUnityContainer). I need some way to say which named type to resolve to.

事情是这样的:(注:并非真正的code)

public ClientModel([NamedDependancy("Client")] IRepository dataAccess)
{
   this.dataAccess = dataAccess;

   .....
}

有没有办法让我的假code的工作?

Is there a way to make my fake code work?

推荐答案

您可以使用或不使用API​​中的名称配置的依存关系,属性或通过配置文件。你没有提到XML上面,所以我会假设你正在使用的API。

You can configure dependencies with or without names in the API, attributes, or via the config file. You didn't mention XML above, so I'll assume you're using the API.

要告诉容器来解决一个名为依赖,你需要使用一个InjectionParameter对象。为了您的ClientModel例如,做到这一点:

To tell the container to resolve a named dependency, you'll need to use an InjectionParameter object. For your ClientModel example, do this:

container.RegisterType<IClientModel, ClientModel>(
    new InjectionConstructor(                        // Explicitly specify a constructor
        new ResolvedParameter<IRepository>("Client") // Resolve parameter of type IRepository using name "Client"
    )
);

这告诉容器当解析ClientModel,调用了一个IRepository参数的构造函数。当解析该参数,解决与另外的类型名称为客户。

This tells the container "When resolving ClientModel, call the constructor that takes a single IRepository parameter. When resolving that parameter, resolve with the name 'Client' in addition to the type."

如果你想使用的属性,你的例子几乎工作的,你只需要改变的属性名称:

If you wanted to use attributes, your example almost works, you just need to change the attribute name:

public ClientModel([Dependency("Client")] IRepository dataAccess)
{
   this.dataAccess = dataAccess;

   .....
}

这篇关于使用Unity我怎么注入一个名为依赖成一个构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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