Skip to content

IoC Package

kobi2294 edited this page May 14, 2019 · 4 revisions

The IoC Package

Overview

This package contains classes that help use Unity as your IoC container and dependency injection mechanism.

IResolver

The IResolver interface is meant to be used as an abstraction over an IoC container. Specifically providing API to resolve an item of type T.

  • Use the Resolve<T> method to resolve an instance of type T
  • Use the Resolve(Type t) method for a reflection based non generic resolution.

UnityResolver

The UnityResolver class provides an implementation of IResolver that is based on UnityContainer. The constructor takes a container as parameter and delegates the resolution requests to it.

AddFactoryFor

It is sometimes required to add a factory method for certain type resolution, where you want to provide these types yourself. Unity can handle this easily with the AddFactory extension method. However, sometimes you need the type of the declaring object, the one that requires the resolution of the target object, as parameter for the factory method. An example for this is when you use Log4Net and you want to pass each object a logger that is defined for that specific object.

MvvmKit adds an additional extension method to IUnityContainer, which allows you to add a factory method that accepts the declaring type as parameter. You use it as follows (an example with Log4Net):

            var container = new UnityContainer();
            container.AddFactoryFor<ILog>(type => LogManager.GetLogger(type));

Now assuming you have a class MyClass that depends on ILog, you can resolve it and it will get a logger that was created specifically for MyClass. You can see the demo in the IoC samples, in the ConsoleDemo project, for a detailed example.

Clone this wiki locally