2014-07-17 79 views
2

我被指示沿着log4net使用AutoFac(而不是Castle Windsor),并且在如何正确使用这些技术时丢失了指令。AutoFac和Log4Net - 注册和使用

使用autofac网站,我有以下LoggerModule

public class LoggingModule : 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) 
    { 
     var t = e.Component.Activator.LimitType; 
     e.Parameters = e.Parameters.Union(
      new[] 
      { 
       new ResolvedParameter((p, i) => p.ParameterType == typeof(ILog), 
       (p, i) => LogManager.GetLogger(t)) 
      }); 
    } 

    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) 
    { 
     // Handle constructor parameters. 
     registration.Preparing += OnComponentPreparing; 

     // Handle properties. 
     registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance); 
    } 
} 

而下面的代码,它注册

builder.RegisterModule(new LoggingModule()); 

这是整合它的正确的方法的例子吗?

我该如何在MVC控制器中使用它?

回答

7

log4net模块与其他任何Autofac module一样 - 您在ContainerBuilder中注册(如您所示)以及所有其他注册。

// EITHER 
builder.RegisterModule<LoggingModule>(); 
// OR 
builder.RegisterModule(new LoggingModule()); 

The documentation on the log4net module page解释了如何可以用来对你的对象注入ILog参数到构造函数或属性。

因此,就像任何其他IoC结构类一样,要使用它,您需要添加一个构造函数或属性以允许它被注入。

public class SomeClassThatNeedsLogging 
{ 
    private ILog _logger; 
    public SomeClassThatNeedsLogging(ILog logger) 
    { 
    this._logger = logger; 
    } 
} 

而且,同样,你可以使用构造函数或财产注入。

public class SomeClassThatNeedsLogging 
{ 
    public ILog Logger { get; set; } 
} 

当您解决注册用户时,Autofac会执行连接。

var someClass = container.Resolve<SomeClassThatNeedsLogging>(); 
// someClass will have the ILog value populated. 

对于控制器,你要注册那些Autofac了,所以你需要做的就是添加的构造函数的参数或公共可写的属性。 MVC集成完成所有的分辨率,所以没有任何手动操作,没有Resolve呼叫或任何东西。

如果现在还不清楚,我建议您花一些时间与the Autofac quick start guide并潜入the rest of the documentation