3

everyone!使用MVC3解析來自Unity 2.0的命名註冊IDependencyResolver

我在使用MVC3 IDependencyResolver從Unity 2.0解析命名註冊時遇到問題。

我配置的類型登記爲

public class Implementations 
{ 
    private IUnityContainer unityContainer; 

    internal Implementations() 
    { 
     this.unityContainer = new UnityContainer(); 
    } 

    public static IUnityContainer GetUnityContainer() 
    { 
     Implementations implementations = new Implementations(); 

     implementations.RegisterImplementations(); 

     return implementations.unityContainer; 
    } 

    private void RegisterImplementations() 
    { 
     this.unityContainer 
      .RegisterType<IService, TestService>() 
      .RegisterType<IService, TestService2>("ts2"); 
    } 
} 

代碼的IDependencyResolver是

public class UnityDependencyResolver : IDependencyResolver 
{ 
    IUnityContainer container = null; 
    string namedRegistration = null; 

    public UnityDependencyResolver(IUnityContainer container, string name) 
    { 
     this.container = container; 
     this.namedRegistration = name; 
    } 

    public object GetService(Type serviceType) 
    { 
     try 
     { 
      return this.container.Resolve(serviceType, this.namedRegistration); 
     } 
     catch 
     { 
      return null; 
     } 
    } 

    public IEnumerable<object> GetServices(Type serviceType) 
    { 
     try 
     { 
      return this.container.ResolveAll(serviceType); 
     } 
     catch 
     { 
      return new List<object>(); 
     } 
    } 
} 

和方法調用中的Application_Start是

protected void Application_Start() 
{ 
    var dependency = 
     new UnityDependencyResolver(Implementations.GetUnityContainer(), "ts2"); 
    DependencyResolver.SetResolver(dependency); 

    AreaRegistration.RegisterAllAreas(); 

    RegisterGlobalFilters(GlobalFilters.Filters); 
    RegisterRoutes(RouteTable.Routes); 
} 

我想這樣做,無論是在UnityDependencyResolver或任何其他方式,是解決我的命名實例或默認實例如果命名不存在。當前代碼總是解析爲默認實例(不命名)。

有沒有人有想法如何做到這一點?

謝謝。

+1

您是否找到解決方案?我需要完全相同! –

回答

1

據我瞭解您嘗試使用IService注入一些控制器:

public class HomeController : Controller 
{ 
    private IService _service; 

    public HomeController(IService service) 
    { 
    _service = service; 
    } 
// .. 
} 

然後,你可以做這樣的(你應該明確地指定命名實例的每個控制器):

private void RegisterImplementations() 
{ 
    _unityContainer 
    .RegisterType<IService, Service1>() 
    .RegisterType<IService, Service2>("ts2") 
    .RegisterType<HomeController>(new InjectionConstructor(new ResolvedParameter<IService>("ts2"))); 
} 

,你不應該傳遞的註冊名稱MVC解析器COS這是沒有意義的(我們只有一個(命名)型控制器默認):

public class UnityDependencyResolver : IDependencyResolver 
{ 
    private readonly IUnityContainer container; 

    public UnityDependencyResolver(IUnityContainer container) 
    { 
    this.container = container; 
    } 

    #region IDependencyResolver Members 

    public object GetService(Type serviceType) 
    { 
    try 
    { 
     return container.Resolve(serviceType); 
    } 
    catch 
    { 
     return null; 
    } 
    } 
// .. 
} 

PS爲什麼你需要一些IService的實例 - 默認和命名?