Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ILogger for Controller is not correctly resolved #21

Open
urajkovic opened this issue Jan 16, 2018 · 3 comments
Open

ILogger for Controller is not correctly resolved #21

urajkovic opened this issue Jan 16, 2018 · 3 comments

Comments

@urajkovic
Copy link

urajkovic commented Jan 16, 2018

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.

@nblumhardt
Copy link
Owner

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!

@alvaromarithompson
Copy link

alvaromarithompson commented Oct 27, 2018

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

@tbraz
Copy link

tbraz commented Aug 4, 2019

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants