简体   繁体   English

如何在ASP.NET Webforms中使用Autofac注入NLog

[英]How to inject NLog using Autofac in ASP.NET Webforms

I have an ASP.NET Webforms project that I've been recently converting to use Dependency Injection via Autofac. 我有一个ASP.NET Webforms项目,最近我将其转换为通过Autofac使用依赖注入。 It has all been going well, that is until I tried to inject my NLog instances. 一切都进行得很好,直到我尝试注入NLog实例为止。 I can't work out how to perform the equivalent of the static GetCurrentClassLogger() method calls with the property injected Logger object. 我不知道如何通过注入的属性Logger对象执行与静态GetCurrentClassLogger()方法调用等效的操作。

Here is my sample code illustrating the problem: 这是说明问题的示例代码:

Global.asax.cs 的Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using Autofac;
using Autofac.Integration.Web;

public class Global : HttpApplication, IContainerProviderAccessor
{
  private static IContainerProvider containerProvider;

  public IContainerProvider ContainerProvider
  {
    get { return containerProvider; }
  }

  void Application_Start(object sender, EventArgs e)
  {
    var builder = new ContainerBuilder();
    Bootstrapper.RegisterInstances(builder);
    containerProvider = new ContainerProvider(builder.Build());
  }
}

Bootstrapper.cs Bootstrapper.cs

using Autofac;

public static class Bootstrapper
{
  public static void RegisterInstances(ContainerBuilder builder)
  {
    builder.RegisterType<Logger>().As<ILogger>().InstancePerRequest();
    builder.RegisterType<MyTestModule>().As<IMyTestModule>().InstancePerRequest();
  }
}

MyTestModule.cs MyTestModule.cs

using System;

public class MyTestModule : IMyTestModule
{
   // was previously: protected static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

  private ILogger _logger;

  public MyTestModule(ILogger logger)
  {
    _logger = logger;
  }

  public void DoSomethingBad()
  {
    try
    {
        int z = 5 / 0;
    }
    catch (Exception ex)
    {
        _logger.Error("Error!", ex);
    }
  }
}

public interface IMyTestModule
{
  void DoSomethingBad();
}

PageBase.cs PageBase.cs

public abstract class PageBase : Page
{
  // was previously: protected static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

  public ILogger Logger { get; set; }

  public IMyTestModule MyTestModuleInstance { get; set; }
}

Default.aspx Default.aspx的

<%@ Page Title="Home" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<html>
  <head></head>
  <body></body>
</html>

Default.aspx.cs Default.aspx.cs

using System;

public partial class _Default : PageBase
{
  protected void Page_Load(object sender, EventArgs e)
  {
    MyTestModuleInstance.DoSomethingBad();
  }
}

You can see in PageBase.cs and MyTestModule.cs I have commented out the previous static calls to create the NLog instance: 您可以在PageBase.csMyTestModule.cs中看到我已经注释掉了以前创建NLog实例的静态调用:

protected static readonly ILogger Logger = LogManager.GetCurrentClassLogger();

They are now simply replaced with the Autofac dependency injected property like this: 现在,将它们简单地替换为Autofac依赖项注入属性,如下所示:

public ILogger Logger { get; set; }

This works in so much that the Logger object gets initialised to an instance of the logger. 这样做的工作量很大,以至于Logger对象被初始化为logger的实例。

How do I perform the equivalent of LogManager.GetCurrentClassLogger() ? 如何执行与LogManager.GetCurrentClassLogger()等效的功能?

Is there something I need to do with NLog modules to achieve this? 我需要使用NLog模块来实现此目的吗? If there is I've not been able to find any specific examples. 如果没有的话,我还找不到任何具体的例子。 Any help would be much appreciated! 任何帮助将非常感激!

Override the AttachTocomponentRegistaration of your Module: 覆盖模块的AttachTocomponentRegistaration

public class AutofacLogInjectionModule : Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Preparing += OnComponentPreparing;
    }

    static void OnComponentPreparing(object sender, PreparingEventArgs e)
    {
        e.Parameters = e.Parameters.Union(new[]
    {
        new ResolvedParameter((p, i) => p.ParameterType == typeof(ILogger), (p, i) => LogManager.GetCurrentClassLogger())
    });
    }

}

And Register this module in your bootstrap: 并在您的引导程序中注册此模块:

builder.RegisterModule(new AutofacLogInjectionModule());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将AutoFac与ASP.Net WebForms一起使用 - Using AutoFac with ASP.Net WebForms 如何在ASP.NET MVC 4中使用Autofac注入HttpContextBase - How to inject HttpContextBase using Autofac in ASP.NET MVC 4 我应该如何在asp.net mvc 5中使用autofac向TokenProvider注入Autorest Client? - How should i inject Autorest Client with TokenProvider using autofac in asp.net mvc 5? 如何使用Autofac注入asp.net mvc3自定义成员资格提供程序? - How can you inject an asp.net mvc3 custom membership provider using Autofac? 如何设置 ASP.Net 3.0 Core Web API 项目以使用 AutoFac 和 NLog? - How do you setup an ASP.Net 3.0 Core Web API project to use AutoFac and NLog? 通过ASP.NET Webforms,OWIN和ASP.NET Identity了解Autofac中间件的使用 - Understanding Autofac middleware usage with ASP.NET Webforms, OWIN and ASP.NET Identity ASP.NET Core 2.0使用Autofac注入Controller - ASP.NET Core 2.0 inject Controller with Autofac 如何使用ASP.NET Web表单在Repeater中显示数据? - How to display data in Repeater using asp.net webforms? 如何使用ASP.NET Webforms在DataRow中呈现按钮? - How to render button in DataRow using ASP.NET Webforms? Asp.net Webforms-如何使用二进制读取器读取文件 - Asp.net Webforms - How to Read a file Using Binary Reader
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM