autofac-serilog-integration icon indicating copy to clipboard operation
autofac-serilog-integration copied to clipboard

ILogger for Controller is not correctly resolved

Open urajkovic opened this issue 7 years ago • 3 comments

When I add ILogger parameter to regular class Worker it is resolved as instance with context Worker and errors are correctly logged with SourceContext set to Worker.

However, when ILogger is parameter of UserController it is resolved as instance without context. So error messages don't contain SourceContext.

API is .NET Core 2.0.

urajkovic avatar Jan 16 '18 17:01 urajkovic

Hi @urajkovic - thanks for the report.

I'm not sure how to approach this, I'm not up-to-date with the Autofac integration for ASP.NET Core 2, so would need some time to debug.

Help/PRs welcome, if anyone's able to take a look.

Thanks again!

nblumhardt avatar Jan 16 '18 22:01 nblumhardt

I've encountered the same problem when trying to use the Autofac serilog integration within an ASP.NET Core 2.1 application - when injecting the ILogger into a Controller, {SourceContext} is blank, but when injecting it into any other class, {SourceContext} works as expected.

2018-10-27 08:56:17.919 INF [] - This is a log line from a controller.
2018-10-27 08:56:17.927 INF [SerilogSample.Test] - This is a log line from a class.

I've put together a basic project that illustrates the problem: @alvaromarithompson/serilog-bug-sample

alvaromarithompson avatar Oct 27 '18 08:10 alvaromarithompson

https://www.strathweb.com/2016/03/the-subtle-perils-of-controller-dependency-injection-in-asp-net-core-mvc/#comment-2702995712

The reason for this is something that we already explained. While controller’s constructor dependencies would be resolved by MVC from the IServiceProvider (so in our case an Autofac adapter), the instance of the controller itself (and its disposal too) is created and owned by the framework, not by the container.

The quickest workaround is to AddControllersAsServices in the configure services method

tbraz avatar Aug 04 '19 22:08 tbraz