我有一个使用Ninject.Web.Mvc2的MVC 2.0应用程序和一个存储库模式(在实体框架模型上构建)。我正在尝试创建一个新的ObjectContext,它只会在请求期间生效。我试图通过以下方式实现这一目标:
protected override IKernel CreateKernel(){
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
return kernel;
}
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
然后我没有足够保持这种通用的想法,所以我开始在BeginRequest中工作:
protected void Application_BeginRequest()
{
string EntityConnectionString = ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
HttpContext.Current.Items.Add(_PerRequestContextObjectKey, new EntityFrameworkContextWrapper(EntityConnectionString));
this.Kernel.Bind<IUserRepository>().To<UserRepository>().WithConstructorArgument("ContextWrapper", HttpContext.Current.Items[_PerRequestContextObjectKey]);
}
Wrapper类只是一个通用对象,用于包含我想在请求结束时杀死的任何内容。在这个特定的情况下,我使用它来创建我的新ObjectContext并实现IDisposable,所以我可以执行以下操作:
protected void Application_EndRequest()
{
foreach (var Item in HttpContext.Current.Items)
{
if (Item.GetType() == typeof(IPerRequestLifetimeObjectWrapper))
{
(Item as IPerRequestLifetimeObjectWrapper).Dispose();
}
}
}
我确信这不是最漂亮的方式,但是在这一点上,我正努力让自己感动,因为我花了很多时间“学习”所有这些东西。
我的控制器然后注入:
public class AdminUserController : Controller
{
// Mark for Ninject
[Inject] public IUserRepository _userRepo { get; set; }
public ViewResult Index( )
{
return View(_userRepo.Get);
}
public ViewResult Edit(Guid UserUID)
{
return View(_userRepo.GetById(UserUID));
}
}
我的存储库也会被注入:
[Inject]
public UserRepository(EntityFrameworkContextWrapper ContextWrapper )
// Mark for Ninject Dependency Injection
// Must receive Wrapper that contains active ObjectContext
{
_db = ContextWrapper.Entities; //Not actually named this, just easier for typing right now
}
当我的Controller在我的UserRepository对象中调用Get方法时,它第一次工作得很好。如果我点击刷新(或者我也猜测回发),_ db是空的。当我尝试单步执行调试器时,我发现在调用Application_BeginRequest()之前调用了Controller Index()方法。我以为我对“管道”有了解(我习惯从WebForms调用页面生命周期),但现在我有点迷失了。有人可以详细说明我的大脑有哪些电线交叉?就像我说的,这可能不是最漂亮的方法,但我只用了大约一个半星期来学习MVC,DI与Ninject,Repository和Entity Framework,所以请不要觉得你在说话如果看起来我打破了一些非常基本的东西。
答案 0 :(得分:1)
为什么不简单地使用InRequestScope?您要做的是为每个请求添加新绑定。这将导致严重的问题。 见https://github.com/ninject/ninject.web.mvc/wiki/Unit-of-work-pattern-with-nhibernate
它是NHilbernate,但您可以使用EntityFramework
执行相同的操作