SignalR中的简单喷油器注册问题 [英] Simple Injector registration problem in SignalR

查看:107
本文介绍了SignalR中的简单喷油器注册问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器中设置DI,如下所示,并绑定到注册IHubContext,如

I set DI in my Controller as shown below and tied to register IHubContext as it seen on

控制器:

Controller:

public class DemoController : Controller
{
    private IHubContext<DemoHub> context;

    public DemoController(IHubContext<DemoHub> context)
    {
        this.context = context;
    }
}


Global.asax:

Global.asax:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();



    container.Register<IHubContext, IHubContext>(Lifestyle.Scoped);

    // or 

    container.Register<IHubContext>(Lifestyle.Scoped);

    // code omitted
}

但是当我调试我的应用程序时,遇到" System.ArgumentException:'给定类型的IHubContext不是具体类型.请使用其他重载之一来注册此类型.参数名称:TImplementation'"错误.那么,如何正确注册IHubContext?

But when I debug my app, encounter "System.ArgumentException: 'The given type IHubContext is not a concrete type. Please use one of the other overloads to register this type. Parameter name: TImplementation'" error. So, how can I register IHubContext properly?

推荐答案

由于ASP.NET MVC尚未为SignalR集线器上下文内置依赖注入,因此必须使用GlobalHost.ConnectionManager获取上下文实例.这样,您可以在创建IHubContext实例的容器中注册一个依赖项.考虑到您输入了中心

Since ASP.NET MVC doesn't have built in dependency injection for SignalR hub context you have to obtain a context instance using GlobalHost.ConnectionManager. With this you can register a dependency with your container that creates IHubContext instance. Considering you have typed hub

public class DemoHub : Hub<ITypedClient>
{
}

和界面

public interface ITypedClient
{
    void Test();
}

注册依赖项如下

container.Register<IHubContext<ITypedClient>>(() =>
{
    return GlobalHost.ConnectionManager.GetHubContext<DemoHub, ITypedClient>();
}, Lifestyle.Scoped);

控制器应该看起来像

public class DemoController : Controller
{
    private IHubContext<ITypedClient> context;

    public DemoController(IHubContext<ITypedClient> context)
    {
        this.context = context;
    }
}

这篇关于SignalR中的简单喷油器注册问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆