vendredi 20 janvier 2017

How implement Strategy/Facade Pattern using Unity Dependecy Injection Web API

How tell to Unity.WebApi dependency injection framework, inject the correct class in the correct controller?

DI Project Container

public class UnityContainerConfig
{

    private static IUnityContainer _unityContainer = null;

    public static IUnityContainer Initialize()
    {
        if (_unityContainer == null)
        {
            _unityContainer = new Microsoft.Practices.Unity.UnityContainer()  
            .RegisterType<IMyInterface, MyClass1>("MyClass1")
            .RegisterType<IMyInterface, MyClass2>("MyClass2")
     }
}

-MVC PROJECT-

public static class UnityConfig
{
    public static void RegisterComponents()
    {            
        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(DependencyInjection.UnityContainer.UnityContainerConfig.Initialize());
    }
}

Controller 1:

 private IMyInterface _myInterface
 ///MyClass1
 public XController(
         IMyInterface myInterface
        )
    {
        _myInterface = myInterface
    }

Controller 2:

 private IMyInterface _myInterface
 ///MyClass2
 public YController(
         IMyInterface myInterface
        )
    {
        _myInterface = myInterface
    }

Aucun commentaire:

Enregistrer un commentaire