.Net Core 2.1 - Cannot access a disposed object.Object name: 'IServiceProvider'
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
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.
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>();