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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With