33

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 {System.ObjectDisposedException: Cannot access a disposed object. Object name: 'IServiceProvider'.

This happens in this bit of code:

public class AppContractResolver : DefaultContractResolver
{

    private readonly IServiceProvider _services;

    public AppContractResolver(IServiceProvider services)
    {
        _services = services;
    }

    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        var httpContextAccessor = _services.GetService<IHttpContextAccessor>();
        var user = httpContextAccessor.HttpContext.User;

        List<JsonProperty> properies = base.CreateProperties(type, memberSerialization).ToList();

        properies = FilterOneClaimGranted(type, properies, user);

        return properies;
    }

It happens on this line:

var httpContextAccessor = _services.GetService<IHttpContextAccessor>();

This did work on .NET Core 2.0

I have tried adding the HttpContextAccessor to my startup, but that did not work.

So, how do I fix this?

Let me know if you need more code. I will happily provide more, but I don't know what you might or might not need, so therefor I did not add a lot of code.'

EDIT

I have added services.AddHttpContextAccessor(); to my startup, but that does not seem to work. Still getting the error.

EDIT 2:

Full stacktrace:

- $exception    {System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'IServiceProvider'.
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ThrowHelper.ThrowObjectDisposedException()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
   at WebAPI.Extensions.AppContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization) in C:\Users\luukw\Desktop\stage\blacky-api\Blacky\Extensions\Resolver\AppContractResolver.cs:line 25
   at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
   at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
   at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.GetContractSafe(Type type)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
   at Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType)
   at Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)}    System.ObjectDisposedException
16
  • 1
    just wanting to check, are you registering it in the .net core 2.1 way of calling services.AddHttpContextAccessor();
    – Gibbon
    May 31, 2018 at 8:40
  • I have tried adding it, but did not work. Still got the same error May 31, 2018 at 8:42
  • Instead calling AddHttpContextAccessor try register it manually, helped in my case: services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>()
    – Vitaly
    May 31, 2018 at 10:10
  • @Vitaly Nope, does not work :( May 31, 2018 at 10:13
  • 2
    You should try to avoid passing in a IServiceProvider to your classes and instead pass in the actual thing you need to use. It solves some edge cases (like yours) and it makes it easier to see what your class is actually using for it's dependencies. May 31, 2018 at 14:04

8 Answers 8

18

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

3
  • Thanks, I have a ServiceLocator and I could make this Change: private static IServiceProvider _provider; public static void Init(IServiceProvider provider) { _provider = provider; } public static T Resolve<T>() => (T)_provider.GetService(typeof(T)); "To:" private static IApplicationBuilder _app; public static void Init(IApplicationBuilder app) { _app = app; } public static T Resolve<T>() => (T)_app.ApplicationServices.GetService(typeof(T)); Jul 12, 2018 at 13:29
  • 2
    OMG: the app.ApplicationServices is the most amazing find! Thank you for the suggestion that saved me even more hours of continued research, trial and error.
    – timmi4sa
    Feb 8, 2021 at 23:25
  • :'( I've spent worth time, but I've improved my patience : D thanks!
    – Zaha
    Nov 24, 2021 at 2:31
13

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>();

4
  • IServiceProvider is registered by the framework. It's the container itself May 31, 2018 at 9:57
  • 2
    @MatanShahar just a FYI the answer was updated and now contains correct info. May 31, 2018 at 14:07
  • using IHttpContextAccessor is not recommended
    – lnaie
    Mar 27, 2023 at 14:36
  • The fact has nothing to do with the answer, The OP wanted to access IHttpContextAccessor in a service, and the answer provides a way to do that correctly. Mar 28, 2023 at 17:18
6

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.

2
  • 12
    Any Github link to this issue?
    – Cheesi
    Apr 24, 2019 at 7:53
  • Bug seems to be gone in .net core 3
    – jjxtra
    Jun 27, 2020 at 15:27
2

For me it works with:

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

and then:

     public void Configure(IApplicationBuilder app, IHttpContextAccessor accessor)
    {
    ...
    ...accessor.HttpContext.RequestService

     ...

    }
2

I was getting this error and it took a long time to resolve, so I am going to post it here.

Here is the code that was throwing the error:

using var context = this.DbFactory.CreateDbContext();                
SqlParameter[] parameter =
{
    new SqlParameter("@ord_cust_id", ordCustId)
};
products = await context.GetProduct.FromSqlRaw<ProductEntity>($"{spName}  @ord_cust_id", parameter).AsNoTracking().ToListAsync();

The exception that was thrown was on the last line. It made no sense as the context was being created by the DbFactory, and so there is no way that it could be disposed already.

After a lot of searching, the scope of the DbFactory was found to be "Transient" so that was changed to Singleton, and the exception was resolved.

This is the code in startup:

 services.AddDbContextFactory<CDSEntities>(options =>
 {                
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
 }, ServiceLifetime.Singleton); //changed to Singlton instead of Transient
1

In my case I didn't have the async await on the rest API method, so it was disposing the IServiceProvider before the end of the call.

0

I was getting a similar exception when trying to get service inside the Startup ➢ ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<INotification>(provider =>
    {
        var hubContext = (IHubContext<NotificationHub>)provider
                  .GetService(typeof(IHubContext<NotificationHub>));

        // ↓↓↓ Exception: cannot access a disposed object. Object name: 'IServiceProvider'.
        var mediator = (IMediator)provider.GetService(typeof(IMediator)); 

        hubContext.SetListener(() =>  
            mediator.Send(new ...);
            ...
        });
    }
    ...
}
  

FYI: NotificationHub is my custom notification class implementing the custom INotificaiton service.


Solved the problem by creating a local scoped service:

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<INotification>(provider =>
    {
        var hubContext = (IHubContext<NotificationHub>)provider
                  .GetService(typeof(IHubContext<NotificationHub>));

          var myScope = provider.CreateScope(); // <<< creating a scoped sertvice
          var mediator = (IMediator)myScope.ServiceProvider.GetService(typeof(IMediator));

          hubContext.SetListener(() =>  
             mediator.Send(new ...);
             ...
        });
    }
    ...
}  
0

In my case, "await" operator was missing in the caller method.

    public async Task<OrderResponse> CreateOrder(){
    //Do something
    var response = **await** CreateOrderItem();
    return response;
}

public async Task<ItemResponse> CreateOrderItem(){
    //Do something
}

"await" was missing in CreateOrder()

1
  • This was useful for me, I had the same thing happen in a controller method.
    – MTAG11
    Jan 7, 2022 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.