[英]Creating a Ninject Kernel in Global.asax where a binding has a dependency on HttpContext
在創建內核時,我不斷收到錯誤“System.Web.HttpException:請求在此上下文中不可用”。 鑒於我的一個綁定依賴於Context,這是有道理的。 顯然,Application_Start上不應出現任何上下文。 我只是想知道是否有人知道如何解決這個問題。
public class NinjectBindings : NinjectModule
{
public override void Load()
{
//Framework
Bind<IJsonLayer>().To<JsonLayer>();
Bind<IBusinessLayer>().To<BusinessLayer>();
//Controllers
Bind<ITeamController>().To<TeamController>();
}
}
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
ReflectionUtility.Kernel = new StandardKernel(new NinjectBindings());
}
}
public class ReflectionUtility
{
private static IKernel _kernel;
public static IKernel Kernel {
set { _kernel = value; }
}
}
public class JsonLayer : IJsonLayer
{
private readonly ITeamController _teamController;
private readonly IBusinessLayer _businessLayer;
public JsonLayer(ITeamController teamController, IBusinessLayer businessLayer)
{
_teamController = teamController;
_businessLayer = businessLayer;
}
}
public class BusinessLayer : IBusinessLayer
{
//this is a super-simplification of what's going on. there are multiple different calls to HttpContext.Current.Request in this class
public BusinessLayer()
{
//This is where it breaks
var sessionUserId = HttpContext.Current.Request.Headers["X-SessionUserId"];
}
}
public class TeamController : ITeamController
{
public void DeleteTeam(int intTeam)
{
throw new NotImplementedException();
}
}
您認為,從Business
層訪問HttpContext
是個好主意嗎? 也許你可以花一些時間進行重構? 例如,像這樣的東西。
從應用程序的角度來看,你可以這樣做:
private void RegisterDependencyResolver()
{
kernel
.Bind<ISession>()
.To<SessionService>()
.InRequestScope()
.WithConstructorArgument(
"context",
ninjectContext => new HttpContextWrapper(HttpContext.Current)
);
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.