views:

147

answers:

2

When I

container.RegisterType<IInterface, MyClass>();

everything works, and all dependent properties annotated with:

[Dependency]

are resolved through the container.

But, I now have an int property that I'd like also to resolve through the container. It's not passed in the constructor, but just as a public property. So I tried this:

container.RegisterType<IInterface, MyClass>(
  new InjectionProperty("PropertyName", 1) 
);

Now that property gets injected, but all the other properties annotated with [Dependency] are null and not resolved. If I use InjectionProperty for one property, do I now have to explicitly declare all the other properties that have the [Dependency] attribute?? Or is there a better way to do this?

Thanks.

A: 

Hello,

registering properties with the API(runtime) will cancel [Dependency] Attributes. You can't use both. But you can use reflection to get properties decorated with the [Dependency] attribute and register them at runtime.

najmeddine
A: 

While @najmeddine is correct, you still can do the following.

Your component:

public class Service : IService
{
    [Dependency("Key")]
    public Int32 Value { get; set; }
}

Registration:

IUnityContainer unity = new UnityContainer()
   .RegisterType<IService, Service>()
   .RegisterInstance("Key", 2010)

Usage is straightforward.

If you now use Unity 2.0 or higher (which was not available for you) and if you need to inject different Values in different areas (bounded contexts) of your application, use container hierarchies:

IUnityContainer child = unity.CreateChildContainer()
    .RegisterInstance("Key", 1900);

And resolve your components on child Unity Container.

More about container hierarchies: http://msdn.microsoft.com/en-us/library/ff660895(PandP.20).aspx

Rationalle