named type not used for constructor injection
- by nmarun
Hi,
I have a simple console application where I have the following setup:
public interface ILogger
{
     void Log(string message);
 }
class NullLogger : ILogger
 {
     private readonly string version;
 public NullLogger()
 {
version = "1.0";
     }
     public NullLogger(string v)
     {
  version = v;
     }
     public void Log(string message)
     {
  Console.WriteLine("NULL " + version + " : " + message);
     }
 }
The configuration details are below:
<type type="UnityConsole.ILogger, UnityConsole" mapTo="UnityConsole.NullLogger, UnityConsole">
     
       
  
       
     
   
 
My calling code looks as below:
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
 section.Containers.Default.Configure(container);
 ILogger nullLogger = container.Resolve();
 nullLogger.Log("hello");
This works fine, but once I give a name to this type something like:
<type type="UnityConsole.ILogger, UnityConsole" mapTo="UnityConsole.NullLogger, UnityConsole" name="NullLogger">
     
       
  
       
     
   
 
The above calling code does not work even if I explicitly register the type using
container.RegisterType<ILogger, NullLogger>();
I get the error:
{"Resolution of the dependency failed, type = \"UnityConsole.ILogger\", name = \"\". Exception message is: The current build operation (build key Build Key[UnityConsole.NullLogger, null]) failed: The parameter v could not be resolved when attempting to call constructor UnityConsole.NullLogger(System.String v). (Strategy type BuildPlanStrategy, index 3)"}
Why doesn't unity look into named instances? To get it to work, I'll have to do:
ILogger nullLogger = container.Resolve("NullLogger");
Where is this behavior documented?
Arun