5

在我的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;
    }

我在想应该为我做这件事,但我在 SignalR 注入时不断收到错误消息

“不能将类型‘SignalR.Ninject.NinjectDependencyResolver’隐式转换为‘Microsoft.AspNet.SignalR.IDependencyResolver’”

知道问题是什么吗?

4

1 回答 1

8

我不确定你是否找到了答案。从 1.0.0 版开始,他们已经改变了 DI 在 SignalR 中的工作方式,并且 SignalR.Ninject 包不起作用 - 我写了一篇关于此的小博客文章:http: //myrandomcodesnippets.wordpress.com/2013/03/ 29/ninject-dependency-injection-with-signalr-1-0-1/

基本上,您需要创建自己的实现,这与 SignalR.Ninject 实现相同:

GlobalHost.DependencyResolver = new SignalRNinjectDependencyResolver(kernel);

当您创建新类时,它将希望从 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));
    }
}

希望这可以帮助。

于 2013-03-29T14:53:10.950 回答