1

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

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

显然 IBookAppConfiguration 可以很容易地配置为 Microsoft Unity 来解决,我们甚至假设它是一个单例。

现在,如何配置 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>
4

1 回答 1

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 知道

于 2011-11-03T14:22:34.740 回答