Kento Kento - 3 months ago 15
C# Question

Dependency Injection On The Fly in ASP.net Core

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?

Answer

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");
                        ...
                    });
            });
Comments