I am trying to create a hosted ASP.net Blazor application and trying to get a logger into my controller.
I have this:
public MyController(ILogger logger) {
_logger = logger;
// more initialization
}
But when I run it, I get:
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyApp.Server.Controllers.MyController'.
As there are a lot of log messages scrolling by, I guess Blazor already initializes a logger.
How do I access this?
By using Blazor route parameters, you can pass values from one page to another page. Use NavigationManager to pass a value and route the parameter to another page. Follow this example to achieve passing values from one page to another.
Blazor WebAssemblyHot Reload reacts to most changes to method bodies, such as adding, removing, and editing variables, expressions, and statements. Changes to the bodies of lambda expressions and local functions are also supported.
The non-generic ILogger
is not registered with the service collection. Instead, you are supposed to inject a generic ILogger<T>
. The generic type argument T
is used to set up the category name that is linked with the logger instance. It allows you to easily see where a log call came from.
Usually, you specify the type that you are using the logger with as the generic type argument. So in your case, you would use ILogger<MyController>
:
public MyController(ILogger<MyController> logger)
{
_logger = logger;
}
Note that there is nothing special to server-side Blazor about this behavior. This is standard ASP.NET Core and the controller is also a normal ASP.NET Core controller.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With