Using the [Dependency] attribute on a class property

Dec 15, 2010 at 5:03 PM

I just started using Unity and have the following question.  I have one class A

public class A
{

   [Dependency]
   public BInterface B
  {
  }

   public A(string parameter)
   {
   }
}

public interface BInterface
{
}

public class B : BInterface
{
   public B(string anotherParameter)
   {
   }
}

As you would have noticed in my class A I have a dependency property to BInterface which is implemented by class B.  Only problem is that class B expects a parameter (anotherParameter) as part of the constructor.  How do I pass this in using the [Dependency] attribute?

Dec 15, 2010 at 9:20 PM

There's currently no option to do specify that value using the Dependency attribute.  You can only pass the name of a registered dependency.  But what you really need is doable.   You just need to register a mapping for BInterface to class B with a constructor injection specifying the value for the anotherParameter.   In the config, it would look something like this:

<register type="BInterface" class="B">
     <constructor>
          <param name="anotherParameter" value="stringValue" />
     </constructor>
</register>  

If using the API approach, you can use the InjectionConstructor class:

container.RegisterType<B, ClassB>(new InjectionConstructor("stringValue"));

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Dec 16, 2010 at 6:47 AM

Hi Sarah,

Thanks for you response, my only problem is that "stringValue" is variable and dynamic.

Thanks

Arjuna.

Dec 16, 2010 at 8:18 AM

In  Unity 2.0, it has the ResolverOverrides feature which allows you to pass the parameter you want to use in the call to Resolve.  So if you want to resolve A with B dependency specifying a value for the anotherParameter parameter, the call to resolve would look something like this:

container.Resolve<A>(new PropertyOverride(container.Resolve<BInterface>(new ParameterOverride("anotherParameter", "newValue"))));

The condition for this is that you previously registered BInterface (with no registration name) with constructor injection configured for the constructor  public B(string anotherParameter)

 

Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.
entlib.support@avanade.com

Dec 17, 2010 at 11:16 AM

arjunam,

Try this:

http://www.neovolve.com/post/2010/04/23/AppSetting-parameter-injection-in-Unity-2.aspx

Regards,

RP