I have implemented Repository pattern with Unit of Work, but i am not able to SaveChanges() and after banging my head, i figured it out that it is due to the fact that my DbContext is different in Unit Of work class and Generic Repository Class. Its successfully adding new DbSet to DbContext in generic Repository method but when it lands in Commit method of UnitOfWork, it have different DbContext so all previous changes to DbContext goes away.
Let me know how i can make single instance of ApplicationDbContext so that it has same DbContext Instance per request. Here is the Code,
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;
}
}
}
Here is my services class,
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();
}
}
Here is my Unity Resolver Class,
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);
}
}
Aucun commentaire:
Enregistrer un commentaire