6

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

Anthony Serdyukov
  • 4,268
  • 4
  • 31
  • 37
  • 2
    What you are looking for is called *auto-registration*, *scanning* or *convention-based registration*. Many DI Containers (like Castle Windsor and StructureMap) support this, but Unity does not. May I recommend a better DI Container? – Mark Seemann Jun 23 '10 at 06:54
  • Thanks, but I'm afraid it is not possible to switch to another DI framework at this moment. Actually, I'm looking for smart BuildUp rather than automatic registration of all my descendants. Of course, auto-registration would let me achieve my goal, too. But taking inheritance into account would be more appropriate behavior I think. – Anthony Serdyukov Jun 23 '10 at 07:05
  • Perhaps you will find this related question (and its answer) useful: http://stackoverflow.com/questions/1769056/does-ms-pnp-unity-scan-for-assemblies-like-structuremap – Mark Seemann Jun 23 '10 at 08:28
  • Thanks, @Mark. However, auto-registration is not what I need. I need injections registered for ancestor to be applied to descendant. I don't want to register descendant at all. Furthermore, descendant could be registered with some specialized injections. And all the injections ("inherited" and "specialized") should be applied. – Anthony Serdyukov Jun 29 '10 at 04:51

1 Answers1

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

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

QrystaL
  • 4,886
  • 2
  • 24
  • 28