[英]Unable to saveChanges: ApplicationDbContext with Repository Pattern + Unit of work
我已經用工作單元實現了存儲庫模式,但是我無法保存SaveChanges(),我一頭撞開后,我發現這是由於我的DbContext在工作單元類和通用存儲庫類中有所不同的事實。 它已成功以通用存儲庫方法將新的DbSet添加到DbContext中,但是當它落入UnitOfWork的Commit方法中時,它具有不同的DbContext,因此以前對DbContext所做的所有更改都消失了。
讓我知道如何制作ApplicationDbContext的單個實例,以便每個請求具有相同的DbContext實例。 這是代碼,
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
}
public abstract class GenericRepository<T> : IGenericRepository<T>
where T : BaseEntity
{
protected DbContext _entities;
protected readonly IDbSet<T> _dbset;
public GenericRepository(DbContext context)
{
_entities = context;
_dbset = context.Set<T>();
}
public virtual T Add(T entity)
{
return _dbset.Add(entity);
}
}
public sealed class UnitOfWork : IUnitOfWork
{
private DbContext _dbContext;
public UnitOfWork(DbContext context)
{
_dbContext = context;
}
public int Commit()
{
// Save changes with the default options
return _dbContext.SaveChanges();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_dbContext != null)
{
_dbContext.Dispose();
_dbContext = null;
}
}
}
這是我的服務班,
public abstract class EntityService<T> : IEntityService<T> where T : BaseEntity
{
IUnitOfWork _unitOfWork;
IGenericRepository<T> _repository;
public EntityService(IUnitOfWork unitOfWork, IGenericRepository<T> repository)
{
_unitOfWork = unitOfWork;
_repository = repository;
}
public virtual void Create(T entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
_repository.Add(entity);
_unitOfWork.Commit();
}
}
這是我的Unity Resolver類,
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IQuestionService, QuestionService>();
container.RegisterType<DbContext, ApplicationDbContext>();
container.RegisterType<IUnitOfWork, UnitOfWork>();
container.RegisterType<IQuestionRepository, QuestionRepository>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
}
}
我更改以下行:
container.RegisterType<DbContext, ApplicationDbContext>();
並替換為以下內容:
container.RegisterType(typeof(DbContext), typeof(ApplicationDbContext), new PerThreadLifetimeManager());
這是魔術和密碼作品:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.