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