二传手/物业注射统一不带属性 [英] Setter / property injection in Unity without attributes

查看:187
本文介绍了二传手/物业注射统一不带属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作所在的统一架构作为IoC容器的项目。我的问题是关于注射可选依赖(在这种情况下,记录器)到使用性财产或setter注入几类。

I am working on a project where the Unity framework is used as the IoC container. My question relates to injecting an optional dependency (in this case a logger) into several classes using property- or setter injection.

我不想杂波我所有的班级,这些可选的依赖关系的构造函数,但我不能找到一个好办法来处理这​​统一。你可以这样做的方式是,根据 MSDN文档,通过增加一个属性的属性:

I do not want to clutter the constructors of all my classes with these optional dependencies, but I cannot find a good way to handle this in Unity. The way you would do this is, according to the MSDN documentation, by adding an attribute to the property:

private ILogger logger; 

[Dependency]
public ILogger Logger
{
get { return logger; }
  set { logger = value; }
}

我觉得这是很丑陋的。在 StructureMap 人可以执行以下操作来设置特定类型的所有属性:

I find this very ugly. In StructureMap one could do the following to set all properties of a given type:

SetAllProperties(policy => policy.OfType<ILog>());

有谁知道是否有可能做同样的事情在Unity?

Does anyone know if it is possible to do something similar in Unity?

编辑:

金主要建议使用这种方法的,也可以是通过code ++实现的。

Kim Major suggests using this approach which can also be achieved through code.

我会很感兴趣的是如何为所有匹配的特性自动完成这方面的例子。

I would be interested in examples of how to do this automatically for all matching properties.

推荐答案

我不喜欢那些属性也

您可以用做所有的配置的统一容器的方法:

You can do all using the Configure method of the unity container:

首先注册类型

unityContainer.RegisterType<MyInterface,MyImpl>(
                     new ContainerControlledLifetimeManager());

如果你有多个构造函数,你必须要这样呢统一调用参数的构造函数(如果没有设置统一会去的最胖的一个)

If you have multiple constructors you'll have to to this so Unity invokes the parameterless constructor (if none set Unity will go for the fattest one)

unityContainer.Configure<InjectedMembers>()
                            .ConfigureInjectionFor<MyImpl>(
                                new InjectionConstructor());

设置属性依赖

Setting property dependency

unityContainer.Configure<InjectedMembers>()
                    .ConfigureInjectionFor<MyImpl>(
                         new InjectionProperty(
                             "SomePropertyName",
                                new ResolvedParameter<MyOtherInterface>()));

配置方法依赖

Configuring method dependency

unityContainer.Configure<InjectedMembers>()
                    .ConfigureInjectionFor<MyImpl>(
                        new InjectionMethod(
                            "SomeMethodName",
                            new ResolvedParameter<YetAnotherInterface>()));

这篇关于二传手/物业注射统一不带属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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