使用unity容器解析NLog实例

时间:2016-10-17 16:22:47

标签: c# dependency-injection unity-container

我有以下课程:

    public class TestInjection
    {

        private ILogger logger;
        public TestInjection(ILogger logger)
        {
            this.logger = logger;
        }

        public void Process()
        {
            try
            {
                int zero = 0;
                int result = 5 / zero;
            }
            catch (DivideByZeroException ex)
            {
                logger.Log(LogLevel.Error, "test message", ex);
                Console.WriteLine("logged message from class");
            }
        }
    }

在我的Program.cs我有代码:

    IUnityContainer container = new UnityContainer();
    container.RegisterType<TestInjection>();

    var myTestClass = container.Resolve<TestInjection>(new ResolverOverride[] { new ParameterOverride("logger", LogManager.GetCurrentClassLogger()) });
    myTestClass.Process();

如何使用unity容器解析LogManager.GetCurrentClassLogger(),如果Logger类的默认构造函数不可访问?

感谢。

PS:这是我第一次体验DI和Unity。

1 个答案:

答案 0 :(得分:4)

以下是我的表现:

            IUnityContainer container = new UnityContainer();
            container.RegisterType<ILogger>( new InjectionFactory(l => LogManager.GetCurrentClassLogger()));
            container.RegisterType<TestInjection>();

            var myTestClass = container.Resolve<TestInjection>(new ResolverOverride[] { new ParameterOverride("logger", container.Resolve<ILogger>()) });
            myTestClass.Process();