Reputation: 15557
So, I'm starting a new enterprise project and want to start with the use of an IoC container. By now the project consist of an MVVM WPF Client and 4 other assemblies (CRM, ReportManager, Security Manager and Repository Manager assembly).
The MVVM client interface is based on a Shell and a series of User Controls (loaded within tabs). Within those user controls I need to instantiate and call one or more of the other assemblies and here goes my question.
Given that it's pretty repetitive to be initializing the assemblies each time I need to use them and that (as I've read here) using a singleton isn't a good idea. It's fine if I use an IoC container (I'm thinking about Windsor) and if its, how do I need to manage the container instance itself? Do I need to create a singleton container instance or just initializing the container on another class (MainView) guarantee that I'll be able to use its registered components from another class?
Upvotes: 0
Views: 379
Reputation: 34349
You shouldn't pass references to the container around your application. Don't call the container; it'll call you.
The only places where you would need a reference to the container are at your composition root (where your application is bootstrapped), and in any factory implementations.
Castle Windsor supports typed factories, so even your factories can be auto-wired to use your container.
Update
You say that you have a shell, that has a series of tabs, each tab showing a UserControl.
If you are using MVVM, then you will have view models and views, and presumably each of these UserControls is effectively a view which is bound to an underlying view model.
If you are using a view model first approach (and you probably should be), then the services that the view model requires (e.g. report manager, security manager etc) should be injected into the view model via its constructor (as an abstraction which has been registered against a concrete implementation in the container).
At the point at which you resolve your shell view model (in your composition root), the container will automatically inject the services that the shell view model requires due to its dependency chain support. These shell dependencies may also include the view models for each of the tabs.
Whenever you need to instantiate further view models, the parent view model can take a dependency on a factory type which returns an instance of this new view model. These factory types will require a reference to your container, but as I mentioned, in the case of Castle Windsor (and other IoC containers), support is provided for the creation of factory types which implicitly resolve via the container.
Upvotes: 2