.Net Core 2.1 - Cannot access a disposed object.Object name: 'IServiceProvider'

前端 未结 5 1199
甜味超标
甜味超标 2020-12-10 01:38

I just migrated .NET Core 2.0 to .NET Core 2.1. Everything went fine, but when I try to login now I get the folowing error:

  • $exception {Syste
相关标签:
5条回答
  • 2020-12-10 01:44

    I would imagine that the IServiceProvider implementation may have been used in a using statement inadvertently somewhere or been disposed outright.

    To test if this is the case you could try to resolve the IHttpContextAccessor right after, or in, the ConfigureServices method.

    If it resolves there you would need to step through to find out where the IServiceProvider is being disposed.

    0 讨论(0)
  • 2020-12-10 01:49

    If you create any transient service, such as services.AddTransient... then .net core will dispose the service provider. This is a bug as of .net core 2.2.

    0 讨论(0)
  • 2020-12-10 01:55

    In my case issue was in Startup.cs

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider services)
    {
       var svc = services.GetService<IService>(); // <-- exception here
    }
    

    just replace services.GetService<>() with app.ApplicationServices.GetService<>()

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
       var svc = app.ApplicationServices.GetService<IService>(); // no exception
    }
    

    hope it helps

    0 讨论(0)
  • 2020-12-10 01:59

    For me it works with:

     public void ConfigureServices(IServiceCollection services)
    {
      …
      services.AddHttpContextAccessor();
      …
    }
    

    and then:

         public void Configure(IApplicationBuilder app, IHttpContextAccessor accessor)
        {
        ...
        ...accessor.HttpContext.RequestService
    
         ...
    
        }
    
    0 讨论(0)
  • 2020-12-10 02:06

    I would suggest that instead of calling services.GetService<IHttpContextAccessor>(), inject IHttpContextAccessor to the constructor and use aprivate field to store the value.

    public AppContractResolver(IServiceProvider services, 
                               IHttpContextAccessor httpContextAccessor)
    {
       _services = services;
       this.httpContextAccessor = httpContextAccessor;
    }
    

    Also HttpContextAccessor has to be registered manually. In RegisterServices in Startup.cs add, services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    0 讨论(0)
提交回复
热议问题