Register Type with Property (injection) Setters

Mar 2, 2009 at 7:17 AM
I have a unity container configured with logging and exception handling extensions, and relevant configuration sections for the app blocks.

I want to resolve a type that is marked up for property injection:
public class IFoo
{
    AnObject AnObj { get; set; }
}

public class Foo : IFoo
{
    [Dependency]
    public ExceptionManager ExceptionManager { get; set; }

    [Dependency]
    public AnObject AnObj { get; set; }
}

var params = new [] { new InjectionProperty( "AnObj", new AnObject() ) };

uContainer.RegisterType<IFoo,Foo>( params );

Now, resolving IFoo should resolve to Foo, with AnObj, and ExceptionManager initialized.

var foo = uContainer.Resolve<IFoo>();

However, ExceptionManager is null. Can you use a combination of injection properties, and automatic resolution?

I can verify that ExceptionManager can be resolved:
var exceptionManager = uContainer.Resolve<ExceptionManager>();
Assert.IsNotNull( exceptionManager ); // Passes

Finally, if I use contstructor injection for ExceptionManager, it is also resolved:
public class Foo : IFoo
{
    private ExceptionManager _exMan;
    public Foo( ExceptionManager exMan )
    { _exMan = exMan; }

    [Dependency]
    public AnObject AnObj { get; set; }
}

Thanks
Kieren

Mar 3, 2009 at 7:33 AM
If you specify InjectionProperties, this overrides the default injection mechanisms. You cannot at this time mix the two; the API / config file will override what you specified with attributes. It was designed this way because otherwise there would be no mechanism for turning off the attributes.

It would be pretty easy to add a little helper method to look for the attributes and register those properties yourself if you want. Or just register those properties directly through the API.



Mar 4, 2009 at 9:22 AM
I can accept that :)

Thanks