c#-Ninject无法通过Application_Start中的DependencyResolver解析
作者:互联网
我一直在努力解决整个上午的问题,但似乎该征询意见了.
我有一个MVC / WebApi / SignalR应用程序.我有一项服务,希望与Web应用程序一起开始.我希望注入这项服务.所以这就是我想要做的:
public static class NinjectWebCommon
{
...
private static void RegisterServices(IKernel kernel)
{
GlobalHost.DependencyResolver = new Microsoft.AspNet.SignalR.Ninject.NinjectDependencyResolver(kernel);
kernel.Bind<PricingService>().ToSelf().InSingletonScope();
}
}
public class Application : HttpApplication
{
protected void Application_Start()
{
...
PricingService pricingService = DependencyResolver.Current.GetService<PricingService>();
}
}
我的问题是定价服务变量为null.
根据this post,此模式应起作用,但不起作用.可能是SignalR依赖解析器的影响,但我不确定.
同时,当我在WebApi控制器中使用构造函数注入时,注入工作正常.
public class MyController : ApiController
{
private readonly PricingService _pricingService;
public MyController (PricingService pricingService)
{
_pricingService = pricingService;
}
}
任何帮助将不胜感激.
解决方法:
感谢Steve的评论,我得以解决此问题.
缺少的部分是在MVC基础结构中注册NinjectDependencyResolver:
private static void RegisterServices(IKernel kernel)
{
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
...
}
这样做之后,DependencyResolver.Current实例更改为NinjectDependencyResolver.
不幸的是,这还没有结束.尝试调用DependencyResolver.Current.GetService< PricingService>()时,我遇到了System.EntryPointNotFoundException.但这在this discussion的帮助下很容易解决.
标签:asp-net-web-api,ninject,c 来源: https://codeday.me/bug/20191028/1955737.html