Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to place and configure IoC container in a WPF application?

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.

like image 256
matori82 Avatar asked Apr 29 '12 13:04

matori82


People also ask

What is IoC container in WPF?

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.

What is the use of IoC container in C#?

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.

What is the need for IoC container?

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.

What is dependency injection in WPF?

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.


1 Answers

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.

like image 83
Filippo Pensalfini Avatar answered Oct 07 '22 02:10

Filippo Pensalfini