简体   繁体   English

使用简单注射器将 controller 注入 SignalR 集线器

[英]Injecting controller into SignalR Hubs using Simple Injector

I want to inject a singleton controller into my hubs using Simple Injector.我想使用 Simple Injector 将 singleton controller 注入我的集线器。

I've already tried the following but I'm getting status 500 as a response now.我已经尝试了以下方法,但我现在得到状态 500 作为响应。

EventDataHub:事件数据中心:

public class EventDataHub : Hub
{
    private static IEventDataController _dataController;
    
    public EventDataHub(IEventDataController dataController)
    {
        _dataController = dataController;
    }
    
    public void Subscribe(string signal)
    {
        _dataController.Subscribe(signal, Context.ConnectionId);
    }
}

Startup:启动:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var container = new Container();
    
        var hybridLifestyle = Lifestyle.CreateHybrid(
                    lifestyleSelector: () => HttpContext.Current != null,
                    trueLifestyle: new WebRequestLifestyle(),
                    falseLifestyle: new LifetimeScopeLifestyle());
    
        container.Register<IEventDataController, EventDataController>(Lifestyle.Singleton);
        container.Register<IHub, EventDataHub>(hybridLifestyle);
    
        container.Verify();
    
        var activator = new SimpleInjectorHubActivator(container);
        
        GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => activator);
    
        app.MapSignalR();
    }
}

Hub activator:集线器激活器:

public class SimpleInjectorHubActivator : IHubActivator
{
    private readonly Container _container;
    
    public SimpleInjectorHubActivator(Container container)
    {
        _container = container;
    }
    
    public IHub Create(HubDescriptor descriptor)
    {
        return (IHub)_container.GetInstance(descriptor.HubType);
    }
}

The Subscribe method seems to be unreachable from the client side. Subscribe方法似乎无法从客户端访问。 The hub constructor is executed.执行集线器构造函数。

Exception stack:异常堆栈:

[MissingMethodException: no parameterless constructor defined for this object] [MissingMethodException:没有为此对象定义无参数构造函数]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeTypeHandle.CreateInstance(RuntimeType 类型, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal&ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113 System.RuntimeType.CreateInstanceSlow(布尔 publicOnly,Boolean skipCheckThis,Boolean fillCache,StackCrawlMark 和 stackMark)+113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +206 System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 System.Activator.CreateInstance(Type type) +11 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +206 System.Activator.CreateInstance(Type type, Boolean nonPublic) +83 System.Activator.CreateInstance(Type type) +11

Edit:编辑:

Moving the DI configuration from Startup.cs to global.asax throws this exception:将 DI 配置从 Startup.cs 移动到 global.asax 会引发以下异常:

[ArgumentNullException: value cannot be null. [ArgumentNullException:值不能为 null。 Parametername: s] System.IO.StringReader..ctor(String s) +11377176参数名称:s] System.IO.StringReader..ctor(String s) +11377176
Microsoft.AspNet.SignalR.Json.JsonSerializerExtensions.Parse(JsonSerializer serializer, String json) +63 Microsoft.AspNet.SignalR.Json.JsonSerializerExtensions.Parse(JsonSerializer 序列化程序,字符串 json)+63
Microsoft.AspNet.SignalR.Hubs.HubRequestParser.Parse(String data, JsonSerializer serializer) +21 Microsoft.AspNet.SignalR.Hubs.HubRequestParser.Parse(字符串数据,JsonSerializer 序列化器)+21
Microsoft.AspNet.SignalR.Hubs.HubDispatcher.OnReceived(IRequest request, String connectionId, String data) +40 Microsoft.AspNet.SignalR.Hubs.HubDispatcher.OnReceived(IRequest request, String connectionId, String data) +40
Microsoft.AspNet.SignalR.<>c__DisplayClass64_1.b__5() +34 Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(Func`1 func) +28 Microsoft.AspNet.SignalR.<>c__DisplayClass64_1.b__5() +34 Microsoft.AspNet.SignalR.TaskAsyncHelper.FromMethod(Func`1 func) +28
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +92 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务)+92
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +58 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务)+58

I finally found the problem:我终于找到了问题:

container.Verify() is breaking the registration of the IHubActivator . container.Verify()正在破坏IHubActivator的注册。 So it has to be called either afterwards, or never.因此必须在之后调用它,或者永远不要调用它。

Additionally I removed the container registration for IHub , as it works without now.此外,我删除了IHub的容器注册,因为它现在可以正常工作。 (I added it because container.Register<IEventDataController, EventDataController>(Lifestyle.Singleton) wasn't working at that time and that fixed it somehow) (我添加它是因为container.Register<IEventDataController, EventDataController>(Lifestyle.Singleton)当时没有工作并且以某种方式修复了它)

So my final code in Startup.cs looks like this:所以我在 Startup.cs 中的最终代码如下所示:

public void Configuration(IAppBuilder app)
{
    var container = new Container();

    container.Register<IEventDataController, EventDataController>(Lifestyle.Singleton);

    var activator = new SimpleInjectorHubActivator(container);
    GlobalHost.DependencyResolver.Register(typeof(IHubActivator), () => activator);

    app.MapSignalR();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM