我已经在 autofac 配置中设置了记录器,但记录器没有被注入(inject)到 Controller 或其他类中。
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。
我可以看到这里发生了两件事:
- 你没有register the controllers在你的容器里
- 和/或你没有set the
DependencyResolver
使用您的 Autofac 容器,这意味着默认 Controller 激活器负责更新您的 Controller ,并且它只能为具有默认 - 无参数 - 构造函数的 Controller 执行此操作
关于c# - 无法使用 Autofac 将 ILogger 注入(inject)类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41210988/