简体   繁体   中英

SignalR client service dependency injection

I have implemented Microsoft.AspNetCore.SignalR.Client as a service. I can successfully inject it and send message to the hub. But I can't figure out how to listen to the hub (receive message) from that specific class.

I can receive message in HubClient with OnBroadcast action.

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
    }
}


How can I receive and process message from MyClass ? How can I make OnBroadcast(string message) work in MyClass so that I can do something with message? I have multiple classes each of which has to process message from the hub.

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?
}
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);
    }
}

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