与Ninject的SignalR依赖解析器问题

时间:2016-08-05 04:01:22

标签: dependency-injection signalr ninject

我们使用Ninject作为Signalr的DI容器。我似乎无法将ITransportHeartbeat注入我的一个班级。我使用此接口来管理Signalr建议的客户端状态。

   public class NinjectSignalRDependencyResolver : DefaultDependencyResolver
    {
        private readonly IKernel _Kernel;

        public NinjectSignalRDependencyResolver(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));
        }
    }

Startup.cs

 public void Configuration(IAppBuilder app)
 {
      var kernel = GetKernel();
      var resolver = new NinjectSignalRDependencyResolver(kernel);
      var config = new HubConfiguration { Resolver = resolver }
      GlobalHost.DependencyResolver = resolver;
      GlobalHost.HubPipeline.AddModule(kernel.Get<ErrorModule>());
      app.MapSignalR(config);

      var bootstrapper = new Bootstrapper();
        bootstrapper.Initialize(() =>
        {
            return kernel;
        });

        ///monitor1 is set to null
        var monitor1=GlobalHost.DependencyResolver.Resolve<IMyClass>();
        //monitor2 is set to null 
        var monitor2=_kernel.Get<IMyClass>();
  }

我的自定义Ninject绑定:

    private IKernel GetKernel()
    {
        if (_kernel != null) return _kernel;
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
        kernel.Load(new HubModule());
        kernel.Load(new LogModule());
        kernel.Load(new DaoModule());
        return kernel;
    }

我自己的班级:

 Public class MyClass : IMyClass
 {  
     ITransportHeartbeat _heartbeat;
     IClientListDao _clientList;

     MyClass(IClientListDao clientList, ITransportHeartbeat heartbeat)
     {
        _hearbeat=heartbeat;
        _clientList=clientList;
     }
     .
     .
  }

在上面的MyClass中,Ninject为IClientDao注入对象,但不为ITransportHeartbeat注入。我没有将此接口绑定到任何内容,因为这是由默认解析程序完成的。我在这做错了什么?为什么默认的解析器没有为ITransportHeartbeat注入一个对象?

1 个答案:

答案 0 :(得分:0)

我最终手动解析了startup.cs中的ITransportHeartbeat:

var myClass=kernel.Get<IMyClass>(
        new ConstructorArgument("heartbeat", resolver.Resolve<ITransportHeartbeat>()));

如果我理解正确,ITransportHeartbeat将由默认依赖项解析程序解析。因此,当我在没有传递任何构造函数参数的情况下执行kernel.Get<IMyClass>()时,Ninject将解析IClientListDao并且默认依赖项解析器会解析ITransportHeartbeat。但后者没有得到解决。