Constructor Injection vs Alternatives

Dec 13, 2010 at 9:06 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<IDataProvider, DatabaseDataProvider> in my module

var dataProvider = UnityContainer.Resolve<IDataProvider>() 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