title: Dependency Injection On The Fly in ASP.net Core
body: <p>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 <code>UseExceptionHandler</code> 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.</p>
  
  <p>For example, lets say I have this code in the <code>Configure</code> method in the <code>Startup</code> class of my ASP.net Core project:</p>
  
  <pre><code>app.UseExceptionHandler(
    builder =&gt;
      {
        builder.Run(
          async context =&gt;
            {
              context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
              context.Response.ContentType = "text/html";
  
              var error = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
              if (error != null)
              {
                // TODO Log Exception.  Would like to do something like this:
                // var logger = ServiceProvider.Resolve&lt;ILogger&gt;();
                // logger.LogCritical("Unhandled Error :"error.Error.ToString());
                await context.Response.WriteAsync($"&lt;h1&gt;Error: {error.Error.Message}&lt;/h1&gt;").ConfigureAwait(false);
              }
            });
      });
  </code></pre>
  
  <p>How can I get an instance of ILogger when I don't have a constructor to pass in ILogger?</p>