Suppose I have an IBookRepository interface and implemented by SybaseAsaBookRepository and XMLBookRepository.
SybaseAsaBookRepository constructor requiers 2 parameters, database user id and password, both values could be retrieved by an IBookAppConfiguration instance. XMLBookRepository constructor needs no parameter.
Apparently IBookAppConfiguration can be easily configured for Microsoft Unity to resole, let's even assume it's a Singleton.
Now, how could I configure the Microsoft Unity, to resolve IBookRepository interface to SybaseAsaBookRepository, with the required 2 constructor parameters properly served?
Sample codes are below:
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>
You can change the parameter list of SybaseAsaBookRepository to accept an instance of IBookAppConfiguration:
public class SybaseAsaBookRepository : IBookRepository
{
public SybaseAsaBookRepository(IBookAppConfiguration configuration)
{
string userID = configuration.GetUserID();
string userPassword = configuration.GetPassword();
...
}
}
Your registration has to be:
<register name="SybaseAsa" type="IBookRepository" mapTo="SybaseAsaBookRepository" />
This can be used because Unity knows