編輯
我有前一段時間一些問題,但現在它似乎工作:
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