Autofac injection of IHubContext SignalR MVC

前端 未结 1 945
长情又很酷
长情又很酷 2021-01-21 01:45

I am trying to get SignalR working with Autofac. I have a repo of a stripped back version of what I have done here:

https://github.com/justsayno/signalr-autofac

相关标签:
1条回答
  • 2021-01-21 02:28

    I've been able to do this, but it's not as clean as I would normally like. The primary issue here is that IHubContext does not reflect what specific type of hub it is...it's just a generic handle. So what I've done is to create a named registration within Autofac to register IHubContext using a specific SignalR hub:

    builder.Register(ctx => 
        ctx.Resolve<IDependencyResolver>()
           .Resolve<IConnectionManager>()
           .GetHubContext<EventHub>())
           .Named<IHubContext>("EventHub");
    

    Then I set up specific registrations for the objects I'll be injecting this hub into. This could be either an ApiController, or perhaps some other service that is then injected into controllers using the standard Autofac/WebApi integration. This "specific" registration is the piece I don't like, but I don't know of a cleaner way around it. Here's what that would look like:

    builder.RegisterType<TaskController>()
           .WithParameter(
               new ResolvedParameter(
                   (pi, ctx) => pi.ParameterType == typeof(IHubContext),
                   (pi, ctx) => ctx.ResolveNamed<IHubContext>("EventHub")
           )
     );
    

    Now Autofac should recognize that you want to inject IHubContext into the TaskController and provide the specific registration named EventHub when injecting it.

    0 讨论(0)
提交回复
热议问题