abp icon indicating copy to clipboard operation
abp copied to clipboard

Database operations not applied from SignalR Hub

Open Chernoskill opened this issue 2 years ago • 6 comments

Is there an existing issue for this?

  • [X] I have searched the existing issues

Description

Using SignalR for a ABP web app, a client invokes a SignalR hub method which in turn conducts database operations (in this case: create and update). Everything works without any errors, but the database opearations are not actually applied to the database.

Questions:

Is this behavior to be expected / normal / supposed to be this way? Is there a more elegant (or, elegant at all :) ) way to call a RESTful API from a SignalR hub and apply database operations?

Code snippet of the SignalR hub, using ABPio's BookStore tutorial project with SignalR applied:

public class BookHub : AbpHub<IBookHub>
{
    [HubMethodName("CreateOrUpdateBook")]
    public async Task CreateOrUpdateBookAsync(CreateUpdateBookDto createDto, Guid? id)
    {
        IBookAppService bookAppService = LazyServiceProvider.LazyGetRequiredService<IBookAppService>();
        BookDto bookDto = id.HasValue ? await bookAppService.UpdateAsync((Guid)id!, createDto) : await bookAppService.CreateAsync(createDto);
        await Clients.All.BookUpdated(bookDto);
    }
}

I have created a github repository to showcase this.

Acme.BookStore

Reproduction Steps

Make client invoke SignalR hub method which conducts database operations

Using the sample project I uploaded: (Run DbMigrator to create database and initial migration) Open Books view (Book Store -> Books) New Book Fill out form Save

Expected behavior

The database operations are applied. In this case, a new book will be inserted or updated and the new dto returned to the frontend by calling all connected clients from the hub method that called the database oeprations.

Actual behavior

The book dto is returned to the clients, but the changes to the database are not applied.

Regression?

No response

Known Workarounds

This can be circumvented by overriding the hub's OnConnectedAsync virtual and querying the database in any form, using a UnitOfWork instance.

public class BookHub : AbpHub<IBookHub>
{
    public async override Task OnConnectedAsync()
    {
        IUnitOfWorkManager uowm = LazyServiceProvider.LazyGetRequiredService<IUnitOfWorkManager>();

        using (IUnitOfWork uow = uowm.Begin())
        {
            IRepository<Book, Guid> bookRepository = uow.ServiceProvider.GetRequiredService<IRepository<Book, Guid>>();
            if (await bookRepository.AnyAsync() == false)
            {
                throw new EntityNotFoundException(typeof(Book));
            }
        }
        await base.OnConnectedAsync();
    }
    //Hub methods
}

Version

8.0.1

User Interface

Angular

Database Provider

EF Core (Default)

Tiered or separate authentication server

None (Default)

Operation System

Windows (Default)

Other information

I suspect this has something to do with SignalR holding an ongoing connection between client(s) and the hub, and this connection not being closed which prevents the application of database operations.

Chernoskill avatar Jan 18 '24 07:01 Chernoskill

You can try:

public class BookHub : AbpHub<IBookHub> , IUnitOfWorkEnabled 
{
    [HubMethodName("CreateOrUpdateBook")]
    public virtual async Task CreateOrUpdateBookAsync(CreateUpdateBookDto createDto, Guid? id)
    {
        IBookAppService bookAppService = LazyServiceProvider.LazyGetRequiredService<IBookAppService>();
        BookDto bookDto = id.HasValue ? await bookAppService.UpdateAsync((Guid)id!, createDto) : await bookAppService.CreateAsync(createDto);
        await Clients.All.BookUpdated(bookDto);
    }
}

See: https://docs.abp.io/en/abp/latest/Unit-Of-Work#begin-a-new-unit-of-work

realLiangshiwei avatar Jan 18 '24 07:01 realLiangshiwei

You can try:

public class BookHub : AbpHub<IBookHub> , IUnitOfWorkEnabled 
{
    [HubMethodName("CreateOrUpdateBook")]
    public virtual async Task CreateOrUpdateBookAsync(CreateUpdateBookDto createDto, Guid? id)
    {
        IBookAppService bookAppService = LazyServiceProvider.LazyGetRequiredService<IBookAppService>();
        BookDto bookDto = id.HasValue ? await bookAppService.UpdateAsync((Guid)id!, createDto) : await bookAppService.CreateAsync(createDto);
        await Clients.All.BookUpdated(bookDto);
    }
}

See: https://docs.abp.io/en/abp/latest/Unit-Of-Work#begin-a-new-unit-of-work

Thank you for the suggestion. Implementing the IUnitOfWorkEnabled interface does not work, database operations are still not applied. Adding the [UnitOfWork] attribute to the hub methods doesn't work, either.

Chernoskill avatar Jan 18 '24 08:01 Chernoskill

You can try this:

public class AbpUnitOfWorkHubFilter :  IHubFilter
{
    public virtual async ValueTask<object?> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object?>> next)
    {
        var unitOfWorkManager = invocationContext.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();
        using (var uow = unitOfWorkManager.Reserve(UnitOfWork.UnitOfWorkReservationName, requiresNew:true))
        {
            var result = await next(invocationContext);
            await uow.CompleteAsync();

            return result;
        }
    }
}

Configure<HubOptions>(options =>
{
    options.AddFilter<AbpUnitOfWorkHubFilter>();
});



public class BookHub : AbpHub<IBookHub>
{
    [HubMethodName("CreateOrUpdateBook")]
    public virtual async Task CreateOrUpdateBookAsync(CreateUpdateBookDto createDto, Guid? id)
    {
        IBookAppService bookAppService = LazyServiceProvider.LazyGetRequiredService<IBookAppService>();
        BookDto bookDto = id.HasValue ? await bookAppService.UpdateAsync((Guid)id!, createDto) : await bookAppService.CreateAsync(createDto);
        await Clients.All.BookUpdated(bookDto);
    }
}

realLiangshiwei avatar Jan 23 '24 13:01 realLiangshiwei

This solved the issue, thank you very much!

Chernoskill avatar Jan 25 '24 10:01 Chernoskill

Thanks! I had the same issue.

BTW: shouldn't this be a part of the ABP as this is the expected behavior?

Rikarin avatar Mar 02 '24 21:03 Rikarin

You can try this:

public class AbpUnitOfWorkHubFilter :  IHubFilter
{
    public virtual async ValueTask<object?> InvokeMethodAsync(HubInvocationContext invocationContext, Func<HubInvocationContext, ValueTask<object?>> next)
    {
        var unitOfWorkManager = invocationContext.ServiceProvider.GetRequiredService<IUnitOfWorkManager>();
        using (var uow = unitOfWorkManager.Reserve(UnitOfWork.UnitOfWorkReservationName, requiresNew:true))
        {
            var result = await next(invocationContext);
            await uow.CompleteAsync();

            return result;
        }
    }
}

Configure<HubOptions>(options =>
{
    options.AddFilter<AbpUnitOfWorkHubFilter>();
});



public class BookHub : AbpHub<IBookHub>
{
    [HubMethodName("CreateOrUpdateBook")]
    public virtual async Task CreateOrUpdateBookAsync(CreateUpdateBookDto createDto, Guid? id)
    {
        IBookAppService bookAppService = LazyServiceProvider.LazyGetRequiredService<IBookAppService>();
        BookDto bookDto = id.HasValue ? await bookAppService.UpdateAsync((Guid)id!, createDto) : await bookAppService.CreateAsync(createDto);
        await Clients.All.BookUpdated(bookDto);
    }
}

Does this work for the lower version? For example 7.0, I applied this code but it didn't work

lijiaxuanabc avatar Mar 21 '24 11:03 lijiaxuanabc