Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SignalR Core integration #631

Closed
dotnetjunkie opened this issue Nov 4, 2018 · 0 comments
Closed

SignalR Core integration #631

dotnetjunkie opened this issue Nov 4, 2018 · 0 comments

Comments

@dotnetjunkie
Copy link
Collaborator

dotnetjunkie commented Nov 4, 2018

To integrate with SignalR Core, you need add the following class to your project:

NOTE: This integration requires Simple Injector >= 4.9.

using Microsoft.AspNetCore.SignalR;
using SimpleInjector.Lifestyles;

public sealed class SimpleInjectorHubActivator<T> : IHubActivator<T> where T : Hub
{
    private readonly Container container;
    private Scope scope;
	
    public SimpleInjectorHubActivator(Container container) => this.container = container;

    public T Create()
    {
        this.scope = AsyncScopedLifestyle.BeginScope(this.container);
        return this.container.GetInstance<T>();
    }

    public void Release(T hub) => this.scope.Dispose();
}

Use the following code to plug these integration points into the SignalR Core pipeline:

// Allows hubs to be registered as Scoped while having transient dependencies (not needed in >= v5.0).
container.Options.UseLoosenedLifestyleMismatchBehavior = true;

services.AddSignalR();
services.AddSimpleInjector(container, options =>
{
});

// Find all Hub implementations and register them as scoped.
var types = container.GetTypesToRegister<Hub>(typeof(MyHub).Assembly);
foreach (Type type in types) container.Register(type, type, Lifestyle.Scoped);

// NOTE: SimpleInjectorHubActivator<T> must be registered as Scoped
services.AddScoped(typeof(IHubActivator<>), typeof(SimpleInjectorHubActivator<>));

TIP: When sending SignalR messages from background threads compared to web requests, you try using IHubContext<THub> instead of the hub class itself, because the hub class, in that case, won't be fully initialized.

This next example shows this:

public class TestHandler : IHandleMessages<MessageSent>
{
    private readonly IHubContext<MyHub> _context;

    public TestHandler(IHubContext<MyHub> context)
    {
        _context = context;
    }

    public async Task Handle(MessageSent message)
    {
        await _context.Clients.All.SendAsync("sendMessage", "Message was sent!");
    }
}

This post might be updated in case we find a better way of integrating with SignalR Core.

In case you have comments or found a bug, please open a new issue.

Repository owner locked and limited conversation to collaborators Nov 4, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

1 participant