为某些基类的所有后代配置Unity注入

时间:2010-06-23 02:08:55

标签: inheritance dependency-injection unity-container

如何配置Unity,以便从某个基类派生的任何类都将通过为基类定义的注入管道。

public abstract class Base
{
    public IDependency Dependency {get;set;}
};

public class Derived1: Base
{
};

public class Derived2: Base
{
};


container.RegisterType<Base>(new InjectionProperty("Dependency", new ResolvedParameter<IDependency>()));
var d1 = container.Resolve<Derived1>();

因此,我需要在Unity中注册基类,而解析派生类,以便为基类指定的所有注入都将应用于派生类。

由于我的项目限制,不允许使用DependencyAttribute装饰基类属性。


Mirror of the question on Unity's codeplex site

1 个答案:

答案 0 :(得分:6)

var container = new UnityContainer();
container
    .RegisterType<IDependency, Dependency1>()
    .RegisterTypes(
        AllClasses
            .FromAssemblies(Assembly.GetExecutingAssembly())
            .Where(t => typeof(Base).IsAssignableFrom(t)),
        getInjectionMembers: _ => new[] { new InjectionProperty("Dependency") });
var d1 = container.Resolve<Derived1>();

注意:您需要支持Registration by convention的Unity 3。