如何在 AutoFac 中使用属性注入? [英] How to use Property Injection with AutoFac?

查看:34
本文介绍了如何在 AutoFac 中使用属性注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制台应用程序中,我使用的是 Log4Net,而在 Main 方法中,我正在获取记录器对象.现在,我想通过让所有类从具有 ILog 属性的 BaseClass 继承并应该通过属性注入而不是构造函数注入设置来使这个日志对象在我的所有类中可用.

In a Console application, I'm using Log4Net and in the Main method I'm getting the logger object. Now, I'd like to make this log object available in all my classes by letting all the classes inherit from a BaseClass which has a ILog property and is supposed to be set by Property Injection rather than Constructor Injection.

我正在使用 AutoFac IoC 容器,如何将我的日志对象注入我的每个类的 Log 属性?

I'm using AutoFac IoC container, how to inject my log Object to the Log property of my every class?

实现这一目标的最佳/最简单的方法是什么?

What's the best/easiest way to achieve this?

有没有办法自动解析类型?

Is there any way to automatically resolve types?

以下是我的测试应用程序:

Below is my test application:

namespace ConsoleApplication1
{
    class Program
    {
        static ILog Log;
        static IContainer Container;

        static void Main(string[] args)
        {                
           InitializeLogger();

           InitializeAutoFac();

            // the below works but could it be done automatically (without specifying the name of each class)?
           Product.Log = Container.Resolve<ILog>();

           // tried below but didn't inject ILog object into the Product
           Container.Resolve<Product>();

           RunTest();

            Console.ReadLine();
        }

        private static void RunTest()
        {
            var product = new Product();
            product.Do();
        }

        private static void InitializeAutoFac()
        {
            var builder = new ContainerBuilder();

            builder.Register(c => Log).As<ILog>();

            builder.RegisterType<Product>().PropertiesAutowired();

            Container = builder.Build();            
        }

        private static void InitializeLogger()
        {
            log4net.Config.XmlConfigurator.Configure();

            Log = LogManager.GetLogger("LoggerName");
        }
    }

    public class Product
    {
        public static ILog Log { get; set; }

        public void Do()
        {
            // this throws exception because Log is not set   
            Log.Debug("some Debug");  
        }
    }
}

推荐答案

使用 属性注入:

builder.Register(c => LogManager.GetLogger("LoggerName"))
       .As<ILog>();

builder.RegisterType<CustomClass>()
       .PropertiesAutowired();

这篇关于如何在 AutoFac 中使用属性注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆