2

Unity 文档指出:

如果开发人员使用 Unity 容器的 Resolve 方法实例化的类具有定义对其他类的一个或多个依赖项的构造函数,则 Unity 容器会自动创建在构造函数的参数中指定的依赖对象实例

这很好,但大多数情况下我不指定注入类,而是指定接口,以保持事物解耦。

那么,当我 .Resolve<>指定接口注入而不是类注入的类时,如何利用 Unity 的自动注入?

即在下面的代码中,当我将我的客户构造函数更改为“ public Customer(ILogger logger) ”时,如何使它工作?

using System;
using Microsoft.Practices.Unity;

namespace TestUnityInjection23
{
    public class Program
    {
        static void Main(string[] args)
        {
            Customer customer1 = new Customer(new BasicLogger());
            //Customer customer2 = new Customer(new AdvancedLogger()); //can't use this since Customer only accepts BasicLogger

            UnityContainer container = new UnityContainer();
            container.RegisterType<Customer>();
            container.RegisterType<ILogger, BasicLogger>();
            Customer customer3 = container.Resolve<Customer>();

            Console.ReadLine();
        }
    }

    public class Customer
    {
        public Customer(BasicLogger logger) //would like to have Customer depend on ILogger here so logger can be swapped out
        {
            logger.WriteToLog("creating the customer");
        }
    }

    public interface ILogger
    {
        void WriteToLog(string text);
    }

    public class BasicLogger : ILogger
    {

        public void WriteToLog(string text)
        {
            Console.WriteLine(text);
        }
    }

    public class AdvancedLogger : ILogger
    {
        public void WriteToLog(string text)
        {
            Console.WriteLine("*** {0} ***", text);
        }
    }

}
4

3 回答 3

1

我从未使用过 Unity,但我知道的所有其他 DI 框架都这样做,而且我确信 Unity 也必须这样做。

您是否尝试过更改 Customer 构造函数并查看它是否有效?因为它应该。

于 2009-03-18T14:28:07.857 回答
1

不确定是否为时已晚,但我认为

使用 (IUnityContainer container = new UnityContainer()) { container.RegisterType();

            container
                .RegisterType<ILogger, BasicLogger>()
                .Configure<InjectedMembers>()
                .ConfigureInjectionFor<Customer>(new InjectionConstructor(typeof(BasicLogger)));

            var customer3 = container.Resolve<Customer>();
        }
        Console.ReadLine();


public class Customer
        {
            public BasicLogger Logger { get; set; }
            public Customer(ILogger logger) 
            {
                logger.WriteToLog("creating the customer");
            }
        }

会成功的

于 2009-08-23T10:24:42.793 回答
0

使用泛型

public interface ILogger<T> where T: class
{

}

public class BasicLogger:ILogger<BasicLogger>
{

}

public class AdvanceLogger:ILogger<AdvanceLogger>
{

}
于 2011-10-19T17:50:05.143 回答