Static class to dependency injection Static class to dependency injection wpf wpf

Static class to dependency injection


Problem

DI is not as simple as you've made it look. There are DI frameworks out there which take care of the DI concern, and they are mature pieces of software.

You can't really do DI yourself without designing a DI container because of the way DI should work

DI solves a few problems, a couple of the main ones are:

  • IoC - ensuring that components aren't tightly coupled by moving the resolution and provision of dependencies outside of the component classes

  • Lifetime scope - ensures that components have a well defined lifetime/lifecycle and that they are correctly instantiated and disposed of at key points in your application

How does it look?

You shouldn't even see the container! - you should only see components dependencies and the rest should look like magic...

DI containers should be very transparent. Your components and services should require their dependencies simply by specifying what the dependencies are (in their constructors)

What's my current problem?

You don't want to be having to manually wire up sub-dependencies with code like this:

public MainWindowViewModel(ILocalizer localizer){    _localizer = localizer;    UC1ViewModel  = new UserControl1ViewModel(localizer); // <-- ouch}

There are a number of problems with the above:

  1. You are making the MainWindowViewModel responsible for creating the UC1ViewModel and managing the lifetime of the object (this isn't always a bad thing as sometimes you want to manage the lifetime of an object in a particular component)

  2. You are coupling the implementation of the MainWindowViewModel to the constructor implementation of UserControl1ViewModel - if you require another dependency in UserControl1ViewModel, suddenly you have to update MainWindowViewModel to inject that dependency, cue a lot of refactoring. This is because you are instantiating the type yourself instead of letting a container do it.

How do containers prevent code like the above?

With any container you should be registering components

The container will track the list of possible components and services and use this registry to resolve dependencies.

It also tracks the dependencies lifecycle (singleton, instanced etc)

Ok I've registered everything, what next?

Once you have registered all your dependencies, you then resolve your root component from the container. This is known as the composition root and should be the 'entry point' for your application (usually the main view or main method).

The container should take care of wiring up and creating the dependencies for everything that stems from that composition root.

Example:

(Pseudo code)

public class ApplicationBootstrapper{    private IContainer _container;    public ApplicationBootstrapper() {        _container = new SomeDIContainer();        _container.Register<SomeComponent>().AsSingleton(); // Singleton instance, same instance for every resolve        _container.Register<SomeOtherComponent>().AsTransient(); // New instance per resolve        // ... more registration code for all your components        // most containers have a convention based registration        // system e.g. _container.Register().Classes().BasedOn<ViewModelBase> etc        var appRoot = _container.Resolve<MainWindowViewModel>();        appRoot.ShowWindow();    }}

Now when your application runs, all dependencies are injected into the root and all dependencies of the root and so on

Your MainWindowViewModel could then specify a dependency on the UC as such:

public MainWindowViewModel(UC1ViewModel vm){}

Notice how the MainWindowViewModel no longer needs an ILocalizer instance, it will be resolved and injected into the UC1ViewModel for you (unless of course you need it).

Couple of points to note

  • You should not pass an instance of the container around. If you are referencing the container in your application code anywhere other than during application startup you are probably doing something wrong

  • Deferred resolution of dependencies is usually achieved with factories (types that are designed specifically to resolve from the container on behalf of your components). The factory should be injected into the component and the component can then call the factory to get the instance it needs. This also allows you to pass arguments to the dependency.

  • Use SOLID principles, depend on abstractions not concrete classes. This way it's much easier to swap out components if you decide to change the way something works (you just change the registration code to use a different concrete class that implements the same interface, et voila, no refactoring the app)

Anything else

This is by no means a concise view of DI, there is a lot to consider, but hopefully it will get you started. As Steven mentioned, if you are planning on redistributing the library you should read up on best practices.

The original post on dos/dont's is here:

Dependency Inject (DI) "friendly" library

Which DI container should you use?

The world is your oyster. I'm a fan of Castle Windsor - it's not the fastest (I can't think of an app I've written where I've ever needed component resolution to be ninja fast...), but it's certainly fully featured.

Update: couple of non queries I didn't really address

Plugins

Castle Windsor has plugin capabilities built in - so you can drop a DLL into your application directory which adds functionality to your application by registering components with the container. Not sure if this applies to your UC class library or not (you could just make the app depend on it unless it needs to actually be a plugin)

Other stuff

There are also quite a lot of MVVM frameworks with several different approaches on view/viewmodel resolution (viewmodel-first, view-first, hybrid approaches).

You may want to consider using one of these to help guide you in structuring your application if you are not already using one (it doesn't sound like you are).


Have a look at this article on localization in WPF applications:

http://www.codeproject.com/Articles/299436/WPF-Localization-for-Dummies

Your localization can be handled via resource assemblies for each language you need to support and the correct one will be used at run-time based on the current culture - or a fallback culture. Your view models can reference the resources and shouldn't care about the specific locale.