编辑
我有前一段时间一些问题,但现在它似乎工作:
Bind<CamelTrapEntities>().To<CamelTrapEntities>().Using<OnePerRequestBehavior>();
而不是使用HTTP模块,你可以使用OnePerRequestBehavior,它会照顾处理当前请求中的上下文。
EDIT 2
OnePerRequestBehavior需要在web.config中注册,因为它取决于太多的HttpModule:
在IIS6:
<system.web>
<httpModules>
<add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
</httpModules>
</system.web>
随着IIS7:
<system.webServer>
<modules>
<add name="OnePerRequestModule" type="Ninject.Core.Behavior.OnePerRequestModule, Ninject.Core"/>
</modules>
</system.webServer>
上一个回答
当你不需要的时候处理上下文是你的责任。 ASP.NET中最流行的方式是每个请求都有一个ObjectContext。我这样做具有的HttpModule:
public class CamelTrapEntitiesHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += ApplicationBeginRequest;
application.EndRequest += ApplicationEndRequest;
}
private void ApplicationEndRequest(object sender, EventArgs e)
{
((CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]).Dispose();
}
private static void ApplicationBeginRequest(Object source, EventArgs e)
{
HttpContext.Current.Items[@"CamelTrapEntities"] = new CamelTrapEntities();
}
}
这是注射规则:
Bind<CamelTrapEntities>().ToMethod(c => (CamelTrapEntities) HttpContext.Current.Items[@"CamelTrapEntities"]);
我的仓库发生的ObjectContext中构造函数:
public Repository(CamelTrapEntities ctx)
{
_ctx = ctx;
}
是什么“似乎工作”是什么意思? – jfar 2010-03-14 02:46:07
@jfar:我在几分钟前检查并调用kernel.Get <>两次给了我请求中的同一个实例。我不记得之前有什么问题,但不知何故,我决定不使用它。与此同时,我下载了新的消息来源,但直到今天才进行检查,所以它得到了正确的修正。 – LukLed 2010-03-14 02:54:00