Unity with base class inheritance

Sep 2, 2011 at 2:24 AM

If I am using a base class hierarchy something like this

public class Base
{
   [Dependency]
   public string PropertyName
   {get;set;}
}

public class DerivedClass: Base
{
}

Once I register the derived class and the base class in the UnityRepository.  Then when instantiating the DerivedClass through the repository will the Dependency attribute be added automatically.  From what I have seen this does not happen.

Sep 2, 2011 at 6:44 AM
Edited Sep 2, 2011 at 6:48 AM

I'm not exactly sure what you mean by "UnityRepository" but this works

 

[TestMethod]
public void ResolveDerivedClassWithPropertyInjectionUsingAttribute()
{
  var container = new UnityContainer();

   container.RegisterType<ILogger, Logger>();

  var baseClass = container.Resolve<BaseClass>();

  Assert.IsNotNull(baseClass.Logger);

  var derivedClass = container.Resolve<DerivedClass>();

  Assert.IsNotNull(derivedClass.Logger);
}

public class BaseClass
{
  [Dependency]
  public ILogger Logger { get; set; }
}

public class DerivedClass : BaseClass
{
}

 

Having said this: I would recommend not to use the DependencyAttribute at all. Property Injection works well without polluting your application classes with references to container related assemblies. Rather consider something like this:

 

[TestMethod]
public void ResolveDerivedClassWithPropertyInjectionUsingConfig()
{
  var container = new UnityContainer();

  container.RegisterType<ILogger, Logger>();

  container.RegisterType<AnotherBaseClass>(new InjectionProperty("Logger"));
  container.RegisterType<AnotherDerivedClass>(new InjectionProperty("Logger"));

  var baseClass = container.Resolve<AnotherBaseClass>();

  Assert.IsNotNull(baseClass.Logger);

  var derivedClass = container.Resolve<AnotherDerivedClass>();

  Assert.IsNotNull(derivedClass.Logger);
}

public class AnotherBaseClass
{
  public ILogger Logger { get; set; }
}

public class AnotherDerivedClass : AnotherBaseClass
{
}

 

That means more verbose configuration but keeps your application classes free of all references to Unity (or any other DI container).