Ninject依赖注入SignalR(Ninject Dependency Injection fo

2019-07-19 06:56发布

在我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’”

任何想法是什么问题?

Answer 1:

我不知道你是否已经找到了答案与否。 他们已经改变DI工作在SignalR为1.0.0版本和SignalR.Ninject包不工作的方式-我写这个小博客文章: http://myrandomcodesnippets.wordpress.com/2013/03/ 29 / ninject依赖性喷射与-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));
    }
}

希望这可以帮助。



文章来源: Ninject Dependency Injection for SignalR