2013-12-16 27 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

相關問題