2013-12-16 26 views
1

我尝试在使用Unity创建新对象时解决两个不同实现的单个接口上的两个依赖关系。我使用ASP.NET MVC 4具有多个依赖性的控制器我将重新下方的虚拟场景:使用Unity解析构造函数中相同接口的多个依赖关系

说我们有一个控制器,它看起来是这样的:

public class HomeController : Controller 
{ 
    public HomeController(IRepository repository, ISomeInterface someInterface1, ISomeInterface someInterface2, IConfiguration configuration) 
    { 
     // Code 
    } 
} 

我需要能够将ISomeInterface解析为两个不同的类,并希望根据名称进行此操作。以下是我迄今为止它不Boostrapper.cs工作:

var someInterface1 = new FirstImplementation(); 
var someInterface2 = new SecondImplementation(); 
container.RegisterInstance(typeof(ISomeInterface), someInterface1); 
container.RegisterInstance(typeof(ISomeInterface), "someInterface2", someInterface2); 

我也看了一下这个帖子,但这似乎并没有解决我的问题之一:http://unity.codeplex.com/discussions/355192我认为这是解决我的一个不同的问题,因为我想在构造函数中自动解析2个依赖关系。

这个问题的任何帮助,将不胜感激,谢谢

回答

0

我想你会得到更好的来取代这两种说法ISomeInterface someInterface1, ISomeInterface someInterface2与唯一一个将得到必要的实现。

它可能是一些继承自IEnumerable<ISomeInterface>的接口。这将允许您列举所有需要的实现。

public interface ISomeInterfaceEnumerator : IEnumerable<ISomeInterface> 
{   
} 

public class HomeController : Controller 
{ 
    public HomeController(IRepository repository, ISomeInterfaceEnumerator someInterfaces, IConfiguration configuration) 
    { 
     // Code 
    } 
} 

或许你可以使用更简单,但不灵活的方法

public interface ISomeInterfaceInstances 
{ 
    ISomeInterface someInterface1 { get; } 
    ISomeInterface someInterface2 { get; } 
} 

public class HomeController : Controller 
{ 
    public HomeController(IRepository repository, ISomeInterfaceInstances someInterfaces, IConfiguration configuration) 
    { 
     // Code 
    } 
} 

这只是想法,但实现可以是各种

2

你可以使用命名为注册;为了做到这一点,有一个名字注册类型(因为你已经做了你的样品中的一部分):

var someInterface1 = new FirstImplementation(); 
var someInterface2 = new SecondImplementation(); 
container.RegisterInstance(typeof(ISomeInterface), "Impl1", someInterface1); 
container.RegisterInstance(typeof(ISomeInterface), "Impl2", someInterface2); 

然后,您可以添加一个依赖属性,您使用指定相关名称的参数:

public class HomeController : Controller 
{ 
    public HomeController(IRepository repository, 
       [Dependency("Impl1")] ISomeInterface someInterface1, 
       [Dependency("Impl2")] ISomeInterface someInterface2, 
       IConfiguration configuration) 
    { 
     // Code 
    } 
} 

欲了解更多信息,请参阅此link

相关问题