c# – 使用Autofac将log4net注入控制器

前端之家收集整理的这篇文章主要介绍了c# – 使用Autofac将log4net注入控制器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
尝试使用Autofac将log4net类注入我的控制器,但是我得到以下异常:

None of the constructors found with ‘Public binding flags’ on
type ‘MvcApplication6.Controllers.HomeController’ can be invoked with the available services and parameters: Cannot resolve parameter ‘log4net.ILog logger’ of constructor ‘Void .ctor(log4net.ILog)’.

我创建了一个模块,使用正确的类型注入Log类:

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

    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)) 
        });
    }
}

然后我在我的ASP.NET MVC Application_Start方法注册该模块:

protected void Application_Start()
{
     ContainerBuilder builder = new ContainerBuilder();
     builder.RegisterControllers(typeof (MvcApplication).Assembly) ;

     var container = builder.Build() ;
     DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 

     builder.RegisterModule(new LogInjectionModule());

     AreaRegistration.RegisterAllAreas();

     RegisterGlobalFilters(GlobalFilters.Filters);
     RegisterRoutes(RouteTable.Routes);
}

我在控制器中添加了一个构造函数,它将ILog作为参数:

namespace MvcApplication6.Controllers
{
   public class HomeController : Controller
   {
      ILog _log;

      public HomeController(ILog logger) 
      {
         _log = logger;
      }

      public ActionResult Index()
      {
         ViewBag.Message = "Welcome to ASP.NET MVC!";

         _log.Info("Log message from Index()");

         return View();
      }

      public ActionResult About()
      {
         _log.Info("Log message from About()");

         return View();
      }
   }
}

我相信我错过了一步,所以任何帮助都会受到赞赏.

解决方法

我不确定这是否会导致您的问题,但您应该在调用builder.Build()之前尝试将模块添加到ContainerBuilder中;

像这样的东西:

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterControllers(typeof (MvcApplication).Assembly) ;
builder.RegisterModule(new LogInjectionModule());

var container = builder.Build() ;
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

另一个建议是不注入记录器.通常当我设计一个类时,使用构造函数依赖项,我尝试表达我正在建模的组件的逻辑业务依赖性.日志记录主要是与应用程序正交的实现细节.至少使用log4net,您可以在需要使用LogManager.GetLogger(类型)创建的日志记录的任何类中拥有静态成员.为了便于添加记录器,您可以使用Visual Studio代码段.

原文链接:https://www.f2er.com/csharp/100242.html

猜你在找的C#相关文章