1
假設我有一個IBookRepository接口並由SybaseAsaBookRepository和XMLBookRepository實現。如何在這種情況下使用Microsoft Unity?
SybaseAsaBookRepository構造函數要求2參數,數據庫用戶標識和密碼,這兩個值都可以由IBookAppConfiguration實例檢索。 XMLBookRepository構造函數不需要參數。
顯然IBookAppConfiguration可以很容易地配置爲Microsoft Unity來分解,我們甚至假設它是一個Singleton。
現在,我該如何配置Microsoft Unity,將IBookRepository接口解析爲SybaseAsaBookRepository,並正確提供了所需的2個構造函數參數?
示例代碼如下所示:
public interface IBookRepository
{
/// <summary>
/// Open data source from Sybase ASA .db file, or an .XML file
/// </summary>
/// <param name="fileName">Full path of Sybase ASA .db file or .xml file</param>
void OpenDataSource(string fileName);
string[] GetAllBookNames(); // just return all book names in an array
}
public interface IBookAppConfiguration
{
string GetUserID(); // assuming these values can only be determined
string GetPassword(); // during runtime
}
public class SybaseAsaBookRepository : IBookRepository
{
public DatabaseAccess(string userID, string userPassword)
{
//...
}
}
<register type="IBookAppConfiguration" mapTo="BookAppConfigurationImplementation">
<lifetime type="singleton"/>
</register>
<register name="SybaseAsa" type="IBookRepository" mapTo="SybaseAsaBookRepository">
<constructor>
<param name="userID" value="??? what shall i put it here???"/>
<param name="userPassword" value="??? what shall i put it here???"/>
</constructor>
</register>
嗨PVitt,感謝您的回覆,問題是用戶ID和密碼不能被硬編碼,它必須從IBookAppConfiguration中檢索。 – athos
我更新了答案... – PVitt
是顯式調用是可能的..但是可以在unity.config中配置邏輯嗎? – athos