title: How to do DI in asp.net core middleware?
body: <p>I am trying to inject dependency into my middleware constructor as follows</p>
  
  <pre><code>public class CreateCompanyMiddleware
  {
      private readonly RequestDelegate _next;
      private readonly UserManager&lt;ApplicationUser&gt; _userManager;
  
      public CreateCompanyMiddleware(RequestDelegate next
          , UserManager&lt;ApplicationUser&gt; userManager
          )
      {
          _next = next;
      }
  
      public async Task Invoke(HttpContext context)
      {
          await _next.Invoke(context);
      }
  }
  </code></pre>
  
  <p>My Startup.cs file looks like</p>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
          options.UseMySql(Configuration.GetConnectionString("IdentityConnection")));
  
      services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()
          .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
          .AddDefaultTokenProviders();
      ...
  
      app.UseMiddleware&lt;CreateCompanyMiddleware&gt;();
  
      ...
  </code></pre>
  
  <p>But I am getting this error</p>
  
  <blockquote>
    <p>An error occurred while starting the application.
    InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Common.Models.ApplicationUser]' from root provider.
    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)</p>
  </blockquote>