How to configure Autofac and SignalR in a MVC 5 application

后端 未结 3 1665
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 05:17

I am trying to configure an MVC 5 application to use SignalR 2.2.x and inject a service into my NotificationsHub. We are using Autofac for MVC but I am not sure

3条回答
  •  一向
    一向 (楼主)
    2020-12-21 05:35

    Install nuget package Autofac.SignalR, for example:

    
    

    Register your hubs

    // during creation of the IContainer, register signalr hubs automatically
    var executingAssembly = Assembly.GetExecutingAssembly();
    builder.RegisterHubs(executingAssembly);
    
    // alternatively register hubs individually
    // ExternallyOwned() ensures SignalR is allowed to control disposal of the hubs rather than Autofac.
    builder.RegisterType().ExternallyOwned();
    

    Set signalr service locator

    // replace the Signalr dependency resolver once your IContainer 'container' is ready
    GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
    
    // or this can alternatively be set in the HubConfiguration instance when using OWIN IAppBuilder map.RunSignalR(hubConfiguration);
    var hubConfiguration = new HubConfiguration
    {
        Resolver = new AutofacDependencyResolver(container),
        //...
    }
    

    For more information:

    https://autofaccn.readthedocs.io/en/latest/integration/signalr.html

    https://docs.microsoft.com/en-us/aspnet/signalr/overview/advanced/dependency-injection

提交回复
热议问题