I am working on a middle sized WPF application (MVVM) that should be extensible and maintainable in the future. Thus I decided to use an IoC container (Unity in this case) to keep things flexible.
However I am not sure where to place and configure Unity in a WPF application.
I guess container should be accessible globally so it should probably go to Application class. But should I make it as static property? Should I configure it in Application_Startup() event handler?
Eg:
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
public static UnityContainer MyUnityContainer;
private void Application_Startup(object sender, StartupEventArgs e)
{
// instantiate and configure Unity
}
}
This way I will be able to access container from any place in the application via static property:
App.MyUnityContainer
I guess this is one way to do it but I am not sure if there are better practices for this issue, specifically for WPF apps.
IoC Container (a.k.a. DI Container) is a framework for implementing automatic dependency injection. It manages object creation and it's life-time, and also injects dependencies to the class.
IoC means that one code calls another; DI goes beyond that and implements IoC by using composition. A DI or IoC container needs to instantiate objects (dependencies) and provide them to the application. To do so, it must deal with constructor injection, setter injection, and interface injection.
The IoC container constructs an object of the selected class and also injects all the dependency objects via a constructor, a property, or a function at execution time and disposes it at a suitable time. This approach helps to create and manage objects manually.
As you know, dependency injection is a form of “inversion of the control” (IoC) programming principle. This means that classes don't create the objects they rely on. DI frameworks have containers responsible for revealing and resolving dependencies.
Have a look at the Composition Root Pattern. What you want to do is to initialize it in your Startup event handler and forget about its existence for the rest of the application.
You are trying to implement the Service Locator Pattern, which according to many is an inferior solution to this problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With