使用EntityFramework和Ninject我需要在每次调用存储库时都处理上下文。我需要这样,每次都会对数据库进行新的调用,而不是使用EF上下文范围。
这是我的测试存储库:
public class VehicleRepositoryTest : IVehicleRepository
{
private DBEntities _context;
public VehicleRepositoryTest(DBEntities context)
{
_context = context;
}
....
public List<TB_VEHICULO> GetAll()
{
return _context.TB_VEHICULO.ToList();
}
这是我如何实现ninject模块。我使用“IntransientScope”的想法是在每次调用后处理上下文:
Kernel.Bind<DBEntities>().ToSelf().InTransientScope();
Kernel.Bind<IVehicleRepository>().To<Test.VehicleRepositoryTest>().InTransientScope();
这个想法是每次调用“GetAll()”时都会创建一个新的上下文,所以每次调用数据库时都会这样做。
但它没有用。如果我打电话给“GetAll()”,并且我得到数据A;然后我将数据库数据A更改为数据B,重新调用“GetAll()”,我仍然获得数据A.
更多信息:
我的应用程序是一个WinForms应用程序,要调用实例化我使用组合模式的注入对象:
public static class CompositionRoot
{
public static IKernel kernel { get; private set; }
public static void WireModule(INinjectModule module)
{
kernel = new StandardKernel(module);
}
public static T Resolve<T>()
{
return kernel.Get<T>();
}
}
并且对存储库的调用是这样的:
_vehicleRepository = CompositionRoot.Resolve<IVehicleRepository>();
var test = _vehicleRepository.GetAll();
我遇到了同样的问题。
我的旧代码:
kernel.Bind(typeof(IUnitOfWork)).To<UnitOfWork>().WithConstructorArgument("context", kernel.Get<MyContext>());
我的新代码:
kernel.Bind<DbContext>().To<MyContext>();
kernel.Bind(typeof(IUnitOfWork)).To<UnitOfWork>();
这项工作对我而言。