0

I find that in WPF it is often not possible to use a DI container in the composite root only. I set up all dependencies in the root but I find the need to instantiate view models that simply cannot be instantiated in the root.

Take custom controls for example that live in tabs or get spawned in new windows. Their view models need to be instantiated by the view itself when it gets active. Many of my view models need a dialog provider which I inject as an interface into the VM constructor.

I am not using the DI container as a service locator. I am a firm believer in constructor injection but as I said I find the need for using the DI container to instantiate view models far beyond the composite root. So far I have been using a static class that hosts the DI container which I can use throughout my app.

I am just wondering how you guys have solved this issue?

Harald
  • 1,007
  • 1
  • 14
  • 27

1 Answers1

2

Am not a expert in DI, but I am good enough knowing that you shouldn't use "DI container" anywhere else than your "BootStrapper" or "Composition Root".

So to answer your question: For some reason if you can't create instance of a Type in "Composition Root" you can always use Abstract Factory pattern

Take a look at this and Implementing an Abstract Factory

Community
  • 1
  • 1
Sriram Sakthivel
  • 72,067
  • 7
  • 111
  • 189
  • Sure. You can create a factory that provides the objects and inject that as a dependency. It means extra code for the factories, lessens readability and what do we gain? We loose the dependency on the DI container. IMHO the effort is in no relation to the gain. Or am I missing something? – Harald Apr 08 '14 at 13:06
  • 1
    It may feel a bit hard to do, and redundant which you can easily get via `ServiceLocator` but mark seemann consider this as [Anti Pattern](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/). You cant say it is not worth, once you do it you'll really feel your code base. Read this comment, here is a benifited folk out of [abstract factory pattern](http://stackoverflow.com/questions/1943576/is-there-a-pattern-for-initializing-objects-created-via-a-di-container/1945023#comment10021765_1945023). So IMO it is really worth doing it, it actually makes your code more obvious and clean. – Sriram Sakthivel Apr 08 '14 at 15:25