簡體   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