SignalR Hubs在触发事件时为空

joh*_*y 5 5 c# dependency-injection inversion-of-control asp.net-core

我写了一个通用集线器,我遇到了一些问题,所以要调试它我决定做一个简单的连接计数如下:

public class CRUDServiceHubBase<TDTO> : Hub, ICRUDServiceHubBase<TDTO>
{
    public const string CreateEventName = "EntityCreated";
    public const string UpdateEventName = "EntityUpdated";
    public const string DeleteEventName = "EntityDeleted";

    protected int _connectionCount = 0;

    public Task Create(TDTO entityDTO)
    {
        return Clients.All.InvokeAsync(CreateEventName, entityDTO);
    }

    public Task Update(TDTO entityDTO)
    {
        return Clients.All.InvokeAsync(UpdateEventName, entityDTO);
    }

    public Task Delete(object[] id)
    {
        return Clients.All.InvokeAsync(DeleteEventName, id);
    }

    public override Task OnConnectedAsync()
    {
        this._connectionCount++;
        return base.OnConnectedAsync();
    }

    public override Task OnDisconnectedAsync(Exception exception)
    {
        this._connectionCount--;
        return base.OnDisconnectedAsync(exception);
    }
}

public class MessagesHub : CRUDServiceHubBase<MessageDTO>
{
    public MessagesHub() : base()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在注册这个课程:

services.AddTransient<ICRUDServiceHubBase<MessageDTO>, MessagesHub>();
Run Code Online (Sandbox Code Playgroud)

我有一个使用它的服务,我正在使用它的实现工厂来订阅它的事件:

services.AddTransient<IMessageDTOService>( (c) => {

    var context = c.GetRequiredService<DbContext>();
    var adapter = c.GetRequiredService<IAdaptable<Message, IMessageDTO, MessageDTO>>();
    var validator = c.GetRequiredService<IValidator<Message>>();
    var entityMetadataService = c.GetRequiredService<IEntityMetadataService<Message>>();

    var service = new MessageDTOService(context, adapter, validator, entityMetadataService);
    var hub = c.GetService<ICRUDServiceHubBase<MessageDTO>>();
    this.RegisterHubsCreate(service, hub);

    return service;
});
Run Code Online (Sandbox Code Playgroud)

当我去开火时,我得到一个空引用:

Microsoft.AspNetCore.SignalR.Hub.Clients.get返回null.

我最好的猜测是因为服务是控制器的依赖,它是在signalR初始化它的客户端之前创建的?

有没有人建议我如何注册我的活动,并填写一个客户端?

joh*_*y 5 15

我发现我需要将IHubContext注入我的集线器,以便在我想调用服务器端时访问客户端.

protected IHubContext<CRUDServiceHubBase<TDTO>> _context;

public CRUDServiceHubBase(IHubContext<CRUDServiceHubBase<TDTO>> context)
{
    this._context = context;
}

public Task Create(TDTO entityDTO)
{
    return this._context.Clients.All.InvokeAsync(CreateEventName, entityDTO);
}
Run Code Online (Sandbox Code Playgroud)

  • 当我在我的服务中注入 IHubContext 时,它正在工作,但是当我将它注入到我的 Hub 中时,它不起作用,我的想法是将 IHubContext 从我的服务发送到 Hub 方法作为参数 (2认同)