Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 520
Anthony Serdyukov Avatar asked Jun 23 '10 02:06

Anthony Serdyukov


1 Answers

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.

like image 168
QrystaL Avatar answered Nov 14 '22 17:11

QrystaL