繁体   English   中英

无法使用Autofac将ILogger注入类

[英]Unable to inject ILogger into classes using Autofac

我已将记录器设置为autofac配置,但记录器未注入控制器或其他类中。

builder.RegisterType<SerilogLogger>()
                .WithParameters(new List<Parameter>
                {
                    new NamedParameter("connectionString", azureConnectionString),
                    new NamedParameter("azureTableName", azureTableName),
                })
                .As<ILogger>().SingleInstance();

HomeController.cs

public class HomeController : Controller
{
    private ILogger logger;

    public HomeController(ILogger logger)
    {
        this.logger = logger;
    }

    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";

        return View();
    }
}

我需要显式访问记录器。 有任何想法吗?

例外详情

No parameterless constructor defined for this object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.

异常很直接,似乎是我的autofac配置出现问题。

您用asp.net-web-api2标记了您的问题,这听起来很奇怪,但是您的代码示例似乎使用了ASP.NET MVC。

我可以看到两件事在这里发生:

  • 您没有在容器中注册控制器
  • 和/或您未DependencyResolver设置为使用Autofac容器,这意味着默认控制器激活器负责更新控制器,并且只能对具有默认-无参数-构造函数的控制器执行此操作

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM