Is it possible to get a dependency on the fly by somehow getting a reference to IServiceProvider, or some class that can resolve dependencies? For example, when handling an exception with UseExceptionHandler
to output something meaningful to the client, I would also like to do some custom logging to note some stuff about the exception that was thrown.
For example, lets say I have this code in the Configure
method in the Startup
class of my ASP.net Core project:
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "text/html";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
// TODO Log Exception. Would like to do something like this:
// var logger = ServiceProvider.Resolve<ILogger>();
// logger.LogCritical("Unhandled Error :"error.Error.ToString());
await context.Response.WriteAsync($"<h1>Error: {error.Error.Message}</h1>").ConfigureAwait(false);
}
});
});
How can I get an instance of ILogger when I don't have a constructor to pass in ILogger?
Dependency Injection in ASP.NET Core: The ASP.NET Core Framework is designed from scratch to support inbuilt support for Dependency Injection. The ASP.NET Core Framework injects objects of dependency classes through constructor or method by using a built-in IoC (Inversion of Control) container.
Some of the dependencies are injected to only the controller action as a parameter. ASP.net core has built-in support for constructor-based dependency. The dependency required by the controller is simply adding a service type to the controller in the constructor. The ASP.net core will identify the service type and try to resolve the type.
The property injection is not supported by the ASP.net core but we call the service instance manually and called service methods. There is another way to get dependency services from the service container. In this method, the service is not injected in the controller constructor or in the action method as a parameter.
ASP.net core can also able to inject the dependency to View. This is very useful to inject service related views such as localization. This method will bypass the controller call and fetch data directly from the service. We can inject the service dependency into the view using the @inject directive. The syntax is as follows to use this directive.
You can access the ServiceProvider
in builder.ApplicationServices
. From there you optain an instance of an ILoggerFactory
and then you create the logger
for your exception handler.
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
...
var lf = builder.ApplicationServices.GetService<ILoggerFactory>();
var logger = lf.CreateLogger("myExceptionHandlerLogger");
logger.LogDebug("I am a debug message");
...
});
});
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