tags:

views:

294

answers:

3

I am still getting started with Unity, and have what seems to be a simple question.

I have a class that has a dependency on two different instances of the same interface. How do I configure and resolve this class?

I.E. Given:

public interface ILogger
{
    void Write(string message);
}
public class ConsoleLogger : ILogger
{
    public void Write(string message) 
    {
        Console.WriteLine(message);
    }
}
public class AnotherLogger : ILogger
{
    public void Write(string message)
    {
        Console.WriteLine(DateTime.Now.ToString() + " " + message);
    }
}
public class CombinedLogger : ILogger
{
    IList<ILogger> _loggers;
    public CombinedLogger(params ILogger[] loggers)
    {
         _loggers = new List<ILogger>(loggers);
    }
    public void Write(string message)
    {
         foreach(var logger in _loggers) logger.Write(message);
    }
}

I know how to configure for ConsoleLogger, and AnotherLogger. I also know how to access them in the actual code. What I seem to be blocking on is figuring out how to configure and use CombinedLogger, passing in the instances of ConsoleLogger and AnotherLogger.

+1  A: 
IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger, ConsoleLogger>();
container.RegisterType<ILogger, AnotherLogger>("another");
container.RegisterType<ILogger, CombinedLogger>("combined");
var instances = container.ResolveAll<ILogger>();
Darin Dimitrov
Ok, I understand all but how CombinedLogger knows which other instances to use when it is created. I.E. I want CombinedLogger to access both ConsoleLogger and AnotherLogger.
David Williams
+1  A: 

You use a named registration.

myContainer.RegisterType("ConsoleLogger"); myContainer.RegisterType("AnotherLogger"); myContainer.RegisterType("CombinedLogger");

Then when you resolve the type, you used the name to get the specific one

public class CombinedLogger : ILogger{    
IList<ILogger> _loggers;    
public CombinedLogger(params ILogger[] loggers)    
{         
_loggers = new List<ILogger>();    
_loggers.Add(myContainer.Resolve(Of ILogger)("ConsoleLogger")
_loggers.Add(myContainer.Resolve(Of ILogger)("AnotherLogger")
}    
public void Write(string message)    
{         
foreach(var logger in _loggers) logger.Write(message);    
}
}
aquillin
+1  A: 

Read the documentation on configuration support for arrays.

RichardOD