Using Simple Injector with SignalR

前端 未结 6 548
迷失自我
迷失自我 2020-12-04 10:50

I thought using my own IoC would be pretty straight forward with SignalR and maybe it is; most likely I\'m doing something wrong. Here\'s my code I have so far:



        
6条回答
  •  被撕碎了的回忆
    2020-12-04 11:32

    In .NET Core 3.x the signalR is now a Transient. You can inject your hub using DI. So you start to map the hub, implement the interface and the hub, and access it's context via DI.

    Startup:

    app.UseSignalR(routes =>
    {
        routes.MapHub(NotificationsRoute); // defined as string
    });
    
    services.AddSignalR(hubOptions =>
    {
        // your options
    })
    

    Then you implement a interface like:

    public interface IYourHub
    {
        // Your interface implementation
    }
    

    And your hub:

    public class YourHub : Hub
    {
        // your hub implementation
    }
    

    Finally you inject the hub like:

    private IHubContext YourHub
    {
        get
        {
            return this.serviceProvider.GetRequiredService>();
        }
    }
    

    Also you can define a service for your hub (middleware) and don't inject the context directly to your class.

    Imagine you defined in the interface the method Message so in your class you can send the message like this:

    await this.YourHub.Clients.Group("someGroup").Message("Some Message").ConfigureAwait(false);
    

    If not implemented in a interface you just use:

    await this.YourHub.Clients.Group("someGroup").SendAsync("Method Name", "Some Message").ConfigureAwait(false);
    

提交回复
热议问题