我正在尝试在MVC4项目的 global.asax 中使用依赖项解析器来获取对 Ninject.Extensions.Logging.ILogger 的引用,但它是抛出 NullReferenceException 。我正在项目的其他地方使用构造函数注入来获取ILogger的实例,并且可以完美地运行。
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
Response.Clear();
var rd = new RouteData();
rd.Values["controller"] = "Error";
rd.Values["action"] = "NotFound";
//this line throws a NullReferenceException with the stack track below
var logger = DependencyResolver.Current.GetService<ILogger>();
IController c = new ErrorController(logger);
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
}
at Ninject.Extensions.Logging.LoggerFactoryBase.GetLogger(IContext context) in c:\Projects\Ninject\ninject.extensions.logging\src\Ninject.Extensions.Logging\LoggerFactoryBase.cs:line 61
at Ninject.Extensions.Logging.LoggerModuleBase.<Load>b__0(IContext context) in c:\Projects\Ninject\ninject.extensions.logging\src\Ninject.Extensions.Logging\LoggerModuleBase.cs:line 26
at Ninject.Activation.Providers.CallbackProvider`1.CreateInstance(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\CallbackProvider.cs:line 45
at Ninject.Activation.Provider`1.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Provider.cs:line 38
at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Ninject.Web.Mvc.NinjectDependencyResolver.GetService(Type serviceType) in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectDependencyResolver.cs:line 56
at System.Web.Mvc.DependencyResolverExtensions.GetService[TService](IDependencyResolver resolver)
at My.WebApp.MvcApplication.Application_EndRequest() in c:\Dev\Project\My.WebApp\Global.asax.cs:line 92
如果我用以下内容替换DependencyResolver行,它可以工作,但是可以创建多个内核实例吗?
var kernel = new StandardKernel();
ILoggerFactory loggerFactory = kernel.Get<ILoggerFactory>();
var logger = loggerFactory.GetCurrentClassLogger();
答案 0 :(得分:2)
您不能Get<>
ILogger
因为在这种情况下它不会被注入任何地方,并且无法评估类型。您有两种选择: