How do I configure Unity to create a class that accepts two different elements of the same type?

I am still starting with Unity and have what seems like a simple question.

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

those. 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 set up for ConsoleLogger and AnotherLogger. I also know how to access them in real code. What I seem to be blocking is figuring out how to set up and use the CombinedLogger by passing in ConsoleLogger and AnotherLogger instances.

0


a source to share


3 answers


Read the documentation on array configuration support .



+1


a source


IUnityContainer container = new UnityContainer();
container.RegisterType<ILogger, ConsoleLogger>();
container.RegisterType<ILogger, AnotherLogger>("another");
container.RegisterType<ILogger, CombinedLogger>("combined");
var instances = container.ResolveAll<ILogger>();

      



+2


a source


You are using 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

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);    
}
}

      

+1


a source







All Articles