SignalR客户端服务依赖注入

时间:2018-03-19 17:35:28

标签: c# dependency-injection .net-core signalr

我已将Microsoft.AspNetCore.SignalR.Client实现为服务。我可以成功注入它并向集线器发送消息。但我无法弄清楚如何从该特定班级收听集线器(接收消息)。

我可以通过HubClient操作在OnBroadcast收到消息。

public class HubClient : IHub
{
    private HubConnection hubConnection;

    private async Task ConnectAsync()
    {
        // Connect

        hubConnection.On<string>("Broadcast", OnBroadcast); 
    }

    public async Task Send(string message)
    {
        await hubConnection.SendAsync("method", message);
    }

    private void OnBroadcast(string message)
    {
        // Received message
    }
}


如何从MyClass接收和处理消息?如何让OnBroadcast(string message)MyClass中工作,以便我可以对消息做些什么?我有多个类,每个类都必须处理来自集线器的消息。

public class MyClass
{
    private readonly IHub hub;

    public MyClass(IHub hub)
    {
        this.hub = hub;
    }

    public Task Send(string message)
    {
        // Sending message to the hub works
        await hub.Send(message);
    }

    // How can I process received messages here?
}

1 个答案:

答案 0 :(得分:0)

public interface IHub
{
    Task Send(string data);

    event Action<string> OnBroadcastAction;
}


public class HubClient : IHub
{
    private HubConnection hubConnection;

    public event Action<string> OnBroadcastAction;

    private async Task ConnectAsync()
    {
        // Connect

        hubConnection.On<string>("Broadcast", OnBroadcast);
    }

    public async Task Send(string message)
    {
        await hubConnection.SendAsync("method", message);
    }

    private void OnBroadcast(string message)
    {
        OnBroadcastAction?.Invoke(message);
    }
}


public class MyClass
{
    private readonly IHub hub;

    public MyClass(IHub hub)
    {
        this.hub = hub;
        hub.OnBroadcastAction += OnBroadcast;
    }

    public Task Send(string message)
    {
        await hub.Send(message);
    }

    private void OnBroadcast(string message)
    {
        Console.WriteLine(message);
    }
}