Anthony Serdyukov
Anthony Serdyukov

Reputation: 4328

Configure Unity Injection for all descendants of some base class

How to configure Unity so that any class derived from some base class would go through injection pipeline defined for base class.

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

Thus, I need to register base class with Unity while resolve derived classes so that all injections specified for base class would be applied to derived classes.

Decorating base class property with DependencyAttribute is not allowed due to my project restrictions.


Mirror of the question on Unity's codeplex site

Upvotes: 6

Views: 3422

Answers (1)

QrystaL
QrystaL

Reputation: 4966

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

Note: you need Unity 3 that supports Registration by convention.

Upvotes: 6

Related Questions