在这种情况下如何使用Microsoft Unity?

时间:2011-11-03 14:13:18

标签: unity-container sybase-asa

假设我有一个IBookRepository接口,并由SybaseAsaBookRepository和XMLBookRepository实现。

SybaseAsaBookRepository构造函数需要2个参数,数据库用户ID和密码,这两个值都可以由IBookAppConfiguration实例检索。 XMLBookRepository构造函数不需要参数。

显然可以轻松配置IBookAppConfiguration以供Microsoft Unity使用,我们甚至假设它是单身人士。

现在,我如何配置Microsoft Unity,以解析到SybaseAsaBookRepository的IBookRepository接口,并正确提供所需的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>

1 个答案:

答案 0 :(得分:0)

您可以更改SybaseAsaBookRepository的参数列表以接受IBookAppConfiguration的实例:

public class SybaseAsaBookRepository : IBookRepository
{
    public SybaseAsaBookRepository(IBookAppConfiguration configuration)
    {
        string userID = configuration.GetUserID();
        string userPassword = configuration.GetPassword();
        ...
    }
}

您的注册必须是:

<register name="SybaseAsa" type="IBookRepository" mapTo="SybaseAsaBookRepository" /> 

这可以使用,因为Unity知道