Signalr: DbContext is disposed when using async task

Created on 30 Jan 2018  ·  26Comments  ·  Source: SignalR/SignalR

Issues related to the Asp.NET Core version of SignalR should be filed in the corresponding SignalR repo: https://github.com/aspnet/?utf8=%E2%9C%93&query=Signalr

Expected behavior

DbContext should be live until the end of Hub method.

Actual behavior

Unhandled Exception: System.ObjectDisposedException: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'SampleDbContext'.
   at Microsoft.EntityFrameworkCore.DbContext.CheckDisposed()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityType()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.get_EntityQueryable()
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)

Steps to reproduce

  1. Using Repository pattern with EntityFrameworkCore
  2. All methods return Task
  3. Call and await repository method inside a Hub method
  4. Should return data successfully

Most helpful comment

@tuyen-vuduc I've already done all that before, but still throws the same error. Is strange...

This is the full exception on the output window.

Excepción producida: 'System.IO.FileLoadException' en Microsoft.Extensions.FileProviders.Physical.dll
Excepción no controlada del tipo 'System.IO.FileLoadException' en Microsoft.Extensions.FileProviders.Physical.dll

Could not load file or assembly 'System.ComponentModel.Primitives, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Any idea? If I start a new Project of web api it runs without problem.

Edit: The missing assembly should be on the output of the bin folder?

Well I solved it turning the .runtimeconfig.json to version 2.0.0, I don't know why the version that's on the output on this file is 2.0.3 and it doesn't works fine. The libraries exists on program files and SDK folders... I'll try to take a look on this days :)

All 26 comments

Hi! I had the same problem. My only working solution is if I use synchronous Hub methods and use Result instead of await.
i.e.:

private bool IsUserInRole(string role)
{
   return userManager.IsInRoleAsync(user, role).Result;
}

When you use await the method gives back the run to the caller. The caller method ends and the DbContext object is disposed and after that the Hub method wants to use the DbContext object.
I'm not quite sure it is the reason but the synchronous method with Result solves the problem.

@docoprusta and @tuyen-vuduc - you'll need to share more of your code.

I assure you that if you properly await the completion of your spawned tasks then what you're hoping to do will work.

Questions that come to mind include...

  1. What's constructing your DbContext? Hub constructor or Hub method or something else?
  2. Are you using a using statement anywhere?
  3. Actually... please just post the code :) You've got a SampleDbContext in your error so presumably it's a fairly small sample for your Hub

As said by a team member to you on another thread here in GitHub, you probably want to post this on Stack Overflow as it sounds more like a code issue than a SignalR issue since SignalR is orthogonal to Entity Framework (they generally have nothing to do with each other unless your own code glues them together)

@IanYates,

I will provide a simple repo to demonstrate the issue, however, it's easy to replicate with my given steps.

This issue happens with MS SQL, not yet able to replicate with SQLite. My workaround is to not use Task in Hub method.

To answer your questions

  1. It's created by ASP.NET via DependencyInjection (constructor injection)
  2. No.
  3. It could be easily created by you with my give steps. ANW, I will create a simple repo for that.

Thanks.

Hello @tuyen-vuduc

Be carefull if you're using an IoC, maybe the thread that's operating with dbContext loose it's internal context. By de definition of the life of the object that's being injected.

For example: When you use castle windsor and use .LifeStylePerWebRequest() method and use async, it loose it's internal context and cause issues with async Task. Maybe you've something similiar on the way?

@Ryujose , you are right. I am using Unity for the whole application. Things work well in WebAPI, but not with SignalR :(. Any workaround?

@tuyen-vuduc @docoprusta mention a workaround and told for a possible issue that has SignalR for Hub dbContext dispose handling (With IoC I pressume) maybe you can make work the application at least with his recommendation as a workaround.

For other hand, can you share a piece of code (Like you told before on this same message chain) with this issue?

Maybe we can help you to diagnose what's happening. It's hard to tell where it is the real error as I never have contributed to the repo directly on code.

Note: Are you sure that dbContext object is being disposed through unity, or you're doing by hand in some instance? Be carefull for DbContext, as it's not thread safe, that's another tip to take in account.

Yes, I had to use Synchronous approach already. Here is the sample repo. https://github.com/NAXAM/chat-xamarin-forms-signalr-quickstart

@tuyen-vuduc I'm trying to start your web api app but I've an issue on it. You know what's happening? I've the last versión of SDK and runtime of .NET Core installed. https://s18.postimg.org/nogjrh9y1/Captura.jpg

@Ryujose,

Error message is very clear.

Plz make sure the missing assembly exist.

Possibly clean/clear bin/obj.

Cheers.

@tuyen-vuduc I've already done all that before, but still throws the same error. Is strange...

This is the full exception on the output window.

Excepción producida: 'System.IO.FileLoadException' en Microsoft.Extensions.FileProviders.Physical.dll
Excepción no controlada del tipo 'System.IO.FileLoadException' en Microsoft.Extensions.FileProviders.Physical.dll

Could not load file or assembly 'System.ComponentModel.Primitives, Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Any idea? If I start a new Project of web api it runs without problem.

Edit: The missing assembly should be on the output of the bin folder?

Well I solved it turning the .runtimeconfig.json to version 2.0.0, I don't know why the version that's on the output on this file is 2.0.3 and it doesn't works fine. The libraries exists on program files and SDK folders... I'll try to take a look on this days :)

Hello @tuyen-vuduc again.

Sorry for the long time of waiting. I've done some adjustments to test your case and I can't reproduce your problem.

I've disabled your authentication via annotation, because when I sign in with the swagger UI the logged user it doesn't being mantained on the session. So I tried to run the "/api/conversations/me" without that and it works without problem.

Please can you take a look on your Security issue or if It's okay, please can you explain to us how to let it works?

Thanks!

@Ryujose,

Thank you for you info.

I will check the authentication.

Why you tried WebAPI? Have you checked out SignalR by running Xamarin.Forms sample?

Yes, but it doesn't works, or at least I can't make it work.

Regards.

:D. Which one doesn't work?

I can run the app on my android emulator but I can't sign in. Are you sure the communication code is implemented with your signalr server? I mean the client on android. And of course the call to the web api to sign in.

Regards.

The project that I'm compiling is Inx.Droid as I remember now for android I suppose that's the example, doesn't it?

Regards.

You have to sign up first if you dont have any accounts before.

On Sun, Mar 11, 2018 at 10:39 PM Jose Luis Guerra Infante <
[email protected]> wrote:

The project that I'm compiling is Inx.Droid as I remember now for android
I suppose that's the example, doesn't it?

Regards.


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/SignalR/SignalR/issues/4071#issuecomment-372124551,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AC9-DPezKf_oZNjPWQV2vrqFTumrF1Jnks5tdUUfgaJpZM4RxqeM
.

>

Thanks & Best Regards,
VŨ ĐỨC TUYẾN (Mr.)
Software Developer
(+84) 98 611 9552
Tuyen.[email protected]

Yes I've done it already, and I've verified the data on database and exists.

The issue has to be in another step.

Regards.

@Ryujose Just having time to try out on a Windows, I couldn't replicate your issue. Could you plz step over to see what happens? I believe there will be error log on the console if you couldn't sign in.

@tuyen-vuduc when I've debugged the Android app I haven't seen an event for the buttons, maybe there's something left to push on the repo you've shared?

As you can see in this MainActivity of your Android App there isn't any event for it https://github.com/NAXAM/chat-xamarin-forms-signalr-quickstart/blob/master/mobile/targets/Inx.Droid/MainActivity.cs

Hey,

It's written in Xamarin.Forms. The VM is here

Hello @Ryujose , @tuyen-vuduc i have a same problem, i can not execute any query to database in SignalR method with EF Core 2.0, signalR preview 2 final

error message: Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances

It looks like most people on this thread are using ASP.NET Core SignalR. If you're writing an ASP.NET Core application, SignalR issues should be filed in https://github.com/aspnet/SignalR .

I'm getting this error on a similar technology to SignalR (PubNub, in my case). The error happens when the listener fires off and tries to access the injected context. Since the listener fires off much later, I'm guessing that the object dispose method is called at some point to close all other open DbContext connections?

@rsmarkvo Check to see that you await your async methods where you call them. That is what solved the problem for me. I hope it helps.

Was this page helpful?
0 / 5 - 0 ratings