简体   繁体   中英

Blazor and Dependency Injection System.objectDisposedException

I have a Blazor server app.

I am using EF framework with Dependency injection. In most cases it works well with no errors. However, I am doing a UI update on a timer, and I get thrown a

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: 'ApplicationDbContext'.'

This is the Code, on the Blazor page it works well for the page load, and then maybe about 10/20 refreshes, then it crashes out.

@code {
    public bool Showmap;

    Machine_Device Device = new Machine_Device();

    [Parameter]
    public string DeviceID { get; set; }

    System.Threading.Timer timer;

    protected override async Task OnInitializedAsync()
    {
        if (DeviceID != null)
        {
            var t = await JsonAction.GetLatest_FullData_MachineDevice(DeviceID);
            Device = t;
        }

        timer =  new System.Threading.Timer(UpdateUI, null, TimeSpan.Zero, TimeSpan.FromSeconds(10));
    }

    private async void UpdateUI(object state)
    {
        var t = await JsonAction.GetLatest_FullData_MachineDevice(DeviceID);

        Device = t;
        InvokeAsync(StateHasChanged);
    }

In my Startup I have set the AppicationDBcontext to Transient - I did research on this. I also set the DeviceJsonActions () to Transient as well rather than scoped, in an attempt to resolve this error.

Startup

services.AddTransient<ApplicationDbContext>();
services.AddTransient<DeviceJsonActions>(); (defined as JsonAction in BlazorPage)

In the DeviceJsonAction class it is defined as follows

public class DeviceJsonActions
{

    private readonly ApplicationDbContext _context;
    public ClaimsPrincipal SignedInIdentity { get; set; }

    public DeviceJsonActions(ApplicationDbContext context)
    {
        _context = context;
    }

any ideas?

I think it maybe the timer executing after the component has been disposed.


@implements IDisposable

....

@code {
   ...

  void IDisposable.Dispose()
  {
    if(timer is not null) // C# 9.0
    {
        timer.Dispose();
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM