Constructor Injection vs Alternatives

Dec 13, 2010 at 10:10 AM

Apologies if this question has been answered before. I've looked around for it but can't find the answer, perhaps because I'm unsure what to search on.

I'm new to using dependency injection frameworks and a little confused about the approach to take under some circumstances. Should I always be looking to inject dependencies and create objects using the UnityContainer.Resolve approach? Or should/could I create "new" instances of an object from a previously contructed object. Say for example I have a DataService which needs to read information from a database. Should I use something like Approach A or Approach B or something else?

Approach A

UnityContainer.RegisterType in my module

var dataProvider = UnityContainer.Resolve() in any classes that require this.

I would still need to pass some further initialisation parameters potentially, say a db name to look up from config.

dataProvider.Initialise(param1, param2);

Approach B

Inside any classes that require this IDataProvider dataProvider = new DatabaseDataProvider(loggingService, configService, param1, param 2);

Now ready to use

Thanks in advance
Dec 14, 2010 at 3:55 AM

If you can create the object by resolving from the container or thru automatic injection, then go for it rather than manually instantiating it and then injecting dependencies using BuildUp.  I don't see any Unity or dependecy injection stuff in your code for Approach B though.

On your Approach A, you can configure the Initialize method to be automatically called as well as the value of its parameters when calling Resolve either through configuration or through API.  This is called method injection.

When using the configuration approach, it would look something like:

<register ....>
    <method name="Initialise">
         <param name="param1" value="stringValue1" />
         <param name="param2" value="stringValue2" />

When using the API approach, you would use the Injection method class.  Or if you don't know the values of the parameter during registration, you can use pass a ParameterOverride instance in the call to Resolve.


Sarah Urmeneta
Global Technologies and Solutions
Avanade, Inc.