Automatic Type Lookup passing constructor parameters

Nov 24, 2011 at 10:32 AM

In automatic type lookups configured in the configuration file, how do I specify constructor parameters?

Nov 25, 2011 at 1:55 AM

Unity will automatically inject concrete dependent types into a constructor.  See Annotating Objects for Constructor Injection for more information.

If you are dealing with interfaces then you will need to configure Unity to resolve the correct concrete types.

Given the following code:

    public interface ILogger
    {
        void Log(string msg);
    }

    public class ConsoleLogger : ILogger
    {

        public void Log(string msg)
        {
            Console.WriteLine(msg);
        }
    }

    public class DebugLogger : ILogger
    {
        public void Log(string msg)
        {
            System.Diagnostics.Debug.WriteLine(msg);
        }
    }

    public class Operator
    {
        private ILogger logger;

        public Operator()
        {
        }
        
        public Operator(ILogger logger)
        {
            this.logger = logger;
        }

        public void Write(string msg)
        {
            logger.Log(msg);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            IUnityContainer container = new UnityContainer();            
            container.LoadConfiguration();

            var op = container.Resolve<Operator>();
            op.Write("Test");
        }
    }

Since Operator takes an ILogger interface we will have to register that interface and map it to a concrete type. The configuration to resolve the ILogger would look like this:

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <namespace name="ConsoleApplication1" />
    <assembly name="ConsoleApplication1" />
    <container>
      <register type="ILogger" mapTo="ConsoleLogger" />
    </container>
  </unity>
</configuration>

If we wanted to add the ability to inject a DebugLogger instead of a ConsoleLogger in a specific case then you could add a new register element:

      <register type="Operator" name="DebugOperator">
        <constructor>
          <param dependencyType="DebugLogger" name="logger"/>
        </constructor>
      </register>

and then you can resolve the object using this code:

 op = container.Resolve<Operator>("DebugOperator");

 

Hopefully this addresses your question.

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com