简体   繁体   English

SignalR的Ninject依赖注入

[英]Ninject Dependency Injection for SignalR

In my NinjectWebCommon.cs file, under CreateKernel method I am applying the injection like this 在我的NinjectWebCommon.cs文件中,在CreateKernel方法下,我正在应用这样的注入

private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);

        // Web API Injection
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);                     

        // SignalR Injection
        GlobalHost.DependencyResolver = new SignalR.Ninject.NinjectDependencyResolver(kernel);

        return kernel;
    }

I was thinking that should do it for me but i keep getting an error at the SignalR injection that 我在想,应该为我做这件事,但我在SignalR注射时不断收到错误

"Cannot implicitly convert type 'SignalR.Ninject.NinjectDependencyResolver' to 'Microsoft.AspNet.SignalR.IDependencyResolver'" “无法将类型'SignalR.Ninject.NinjectDependencyResolver'隐式转换为'Microsoft.AspNet.SignalR.IDependencyResolver'”

Any idea what the problem is? 知道问题是什么吗?

I am not sure if you have found the answer or not. 我不确定你是否找到了答案。 They have changed the way DI works in SignalR as of version 1.0.0 and the SignalR.Ninject packages doesn't work - I have written a small blog post on this: http://myrandomcodesnippets.wordpress.com/2013/03/29/ninject-dependency-injection-with-signalr-1-0-1/ 他们已经改变了DI在版本1.0.0中的工作方式,并且SignalR.Ninject软件包不起作用 - 我已经写了一篇关于此的小博客文章: http ://myrandomcodesnippets.wordpress.com/2013/03/ 29 / ninject依赖性喷射与-signalr-1-0-1 /

Basically you need to create your own implementation of this which is the same as the SignalR.Ninject implementation: 基本上你需要创建自己的实现,这与SignalR.Ninject实现相同:

GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel);

When you create the new class it will want to inherit from IDependancyResolver don't bother with this and use: 当你创建新类时,它希望从IDependancyResolver继承而不用这个并使用:

public class SignalRNinjectDependencyResolver : DefaultDependencyResolver
{
    private readonly IKernel _kernel;

    public SignalRNinjectDependencyResolver(IKernel kernel)
    {
        _kernel = kernel;
    }

    public override object GetService(Type serviceType)
    {
        return _kernel.TryGet(serviceType) ?? base.GetService(serviceType);
    }

    public override IEnumerable<object> GetServices(Type serviceType)
    {
        return _kernel.GetAll(serviceType).Concat(base.GetServices(serviceType));
    }
}

Hope this helps. 希望这可以帮助。

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

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