Dumb Injection / Constructor Question

Feb 6, 2009 at 1:32 AM
Hi all,

I don't quite understand how does Unity handle different implementation with different constructors. For example I have an interface ILog to handle logging functions, there are different implementations, such as XmlLog, DatabaseLog and so on. In C# code I may have something like:

interface ILog {
    void LogMessage(string message);

class XmlLog : ILog {
    private string XmlFile;
    public XmlLog(string XmlFile) {
        this.XmlFile = XmlFile;

    public void LogMessage(string message) {
        // build Xml Document an save to XmlFile

class DatabaseLog : ILog {
    private Database dbInstance;
    public DatabaseLog(Database dbInstance) {
        this.dbInstance = dbInstance;

    public void LogMessage(string message) {
        // save to dbInstance database

I understand I can register to container like:
IUnityContainer container = new UnityContainer();
container.RegisterType<ILog, XmlLog>("Xml");
container.RegisterType<ILog, DatabaseLog>("DB");

In my code, I need to resolve one instance bases on some criteria, for example:
// how does Unity handle my constructor here?
ILog myLog = container.Resolve<ILog>("Xml");

Now, my real questions in this situation how can I really pass constructor parameter to my instance?

Feb 6, 2009 at 2:24 AM
There's no support for passing parameters to the Resolve method.  What can be done in Unity is to pass the parameters to the constructors in the RegisterType method..

    IUnityContainer container = new UnityContainer();
    container.RegisterType<ILog, XmlLog>("Xml", new InjectionConstructor("myxmlfile.xml"));
    ILog myLog = container.Resolve<ILog>("Xml");

This will automatically give you an instance of ILog of type XmlLog with its XmlFile field value set to "myxmlfile.xml".

Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.
Feb 6, 2009 at 2:38 AM
Thanks a lot, Sarah!
Mar 19, 2009 at 6:00 PM

How do I initialize based on parameters at the runtime. 
It is usually the case where you have to initialize the class before using it based on certain criteria. How do we handle these scenarios.