Take the 2-minute tour ×

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 name="SybaseAsa" type="IBookRepository" mapTo="SybaseAsaBookRepository"> 
        <param name="userID" value="??? what shall i put it here???"/> 
        <param name="userPassword" value="??? what shall i put it here???"/> 
share|improve this question

1 Answer 1

up vote 0 down vote accepted

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

share|improve this answer
Hi PVitt, thanks for your reply, the problem is user id and pasword cannot be hard-coded, it has to be retrieved from IBookAppConfiguration. –  athos Nov 4 '11 at 3:01
I updated the answer... –  PVitt Nov 4 '11 at 11:51
yeah explicit call is possible.. but is it possible to config the logic in unity.config ? –  athos Nov 8 '11 at 8:37

Your Answer


