我将 Ninject 用于 DI,并将 IDbContext 作为构造函数参数注入到我的存储库中。我得到一个“无法定义两个对象之间的关系,因为它们附加到不同的 ObjectContext 对象。” 尝试执行以下操作时出错:
这是我的控制器的操作方法:
public ActionResult BindSpace(int spaceId, int managerId)
{
Space space = _spaceService.GetSpace(spaceId);
Manager manager = _managerService.GetManager(managerId);
if (space != null && manager != null)
{
_spaceService.BindManager(space, manager);
}
return RedirectToAction("GetSpaceBindingForm", new { id = space.Id });
}
这是服务方法:
public void BindManager(Space space, Manager manager)
{
if (space != null && manager != null)
{
space.Managers.Add(manager);
_spaceRepo.Update(space);
}
}
添加和更新非相关实体时没有问题。
我使用时没有问题:
ninjectKernel.Bind<IDbContext>().To<SPBSObjectContext>().InSingletonScope().WithConstructorArgument("nameOrConnectionString", "ShoppingPointBrowsingSystem");
我在网上搜索,每个人都实现并使用了 NinjectModule 抽象基类,但我有以下代码。我在这里做错了什么?
这是注入部分:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
// HTTP Context
ninjectKernel.Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current));
// Context
ninjectKernel.Bind<IDbContext>().To<SPBSObjectContext>().InRequestScope().WithConstructorArgument("nameOrConnectionString", "ShoppingPointBrowsingSystem");
// Repositories
ninjectKernel.Bind<IRepository<Admin>>().To<EfRepository<Admin>>().InRequestScope();
ninjectKernel.Bind<IRepository<Manager>>().To<EfRepository<Manager>>().InRequestScope();
ninjectKernel.Bind<IRepository<ShoppingCenterSpace>>().To<EfRepository<ShoppingCenterSpace>>().InRequestScope();
ninjectKernel.Bind<IRepository<IndependentStoreSpace>>().To<EfRepository<IndependentStoreSpace>>().InRequestScope();
ninjectKernel.Bind<IRepository<Space>>().To<EfRepository<Space>>().InRequestScope();
// Services
ninjectKernel.Bind<IAuthenticationService<Admin>>().To<AdminFormsAuthenticationService>();
ninjectKernel.Bind<IAdminService>().To<AdminService>();
ninjectKernel.Bind<IManagerService>().To<ManagerService>();
ninjectKernel.Bind<IShoppingCenterSpaceService>().To<ShoppingCenterSpaceService>();
ninjectKernel.Bind<IIndependentStoreSpaceService>().To<IndependentStoreSpaceService>();
ninjectKernel.Bind<ISpaceService>().To<SpaceService>();
}
}