zoukankan      html  css  js  c++  java
  • Autofac log4net Integration Module

    log4net Integration Module

    While there is no specific assembly for log4net support, you can easily inject log4net.ILog values using a very small custom module.

    This module is also a good example of how to use Autofac modules for more than simple configuration - they’re also helpful for doing some more advanced extensions.

    Here’s a sample module that configures Autofac to inject ILog parameters based on the type of the component being activated. This sample module will handle both constructor and property injection.

    public class LoggingModule : Autofac.Module
    {
      private static void InjectLoggerProperties(object instance)
      {
        var instanceType = instance.GetType();
    
        // Get all the injectable properties to set.
        // If you wanted to ensure the properties were only UNSET properties,
        // here's where you'd do it.
        var properties = instanceType
          .GetProperties(BindingFlags.Public | BindingFlags.Instance)
          .Where(p => p.PropertyType == typeof(ILog) && p.CanWrite && p.GetIndexParameters().Length == 0);
    
        // Set the properties located.
        foreach (var propToSet in properties)
        {
          propToSet.SetValue(instance, LogManager.GetLogger(instanceType), null);
        }
      }
    
      private static void OnComponentPreparing(object sender, PreparingEventArgs e)
      {
        e.Parameters = e.Parameters.Union(
          new[]
          {
            new ResolvedParameter(
                (p, i) => p.ParameterType == typeof(ILog),
                (p, i) => LogManager.GetLogger(p.Member.DeclaringType)
            ),
          });
      }
    
      protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
      {
        // Handle constructor parameters.
        registration.Preparing += OnComponentPreparing;
    
        // Handle properties.
        registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance);
      }
    }

    Performance Note: At the time of this writing, calling LogManager.GetLogger(type) has a slight performance hit as the internal log manager locks the collection of loggers to retrieve the appropriate logger. An enhancement to the module would be to add caching around logger instances so you can reuse them without the lock hit in the LogManager call.

  • 相关阅读:
    浅谈算法和数据结构: 二 基本排序算法
    ExecuteScalar()方法的使用
    as和强制类型转换的区别
    duilib入门简明教程 -- 自绘标题栏(5)
    duilib入门简明教程 -- 响应按钮事件(4)
    duilib入门简明教程 -- 第一个程序 Hello World(3)
    duilib入门简明教程 -- VS环境配置(2)
    duilib入门简明教程 -- 前言(1)
    linux 查看 PHP 的默认版本。
    mui
  • 原文地址:https://www.cnblogs.com/lenmom/p/8902557.html
Copyright © 2011-2022 走看看