У меня есть шаблон Generic Repository с UnitOfWork, и я использую IoC. Помимо базовых методов, используемых репозиторием, у меня есть некоторые пользовательские методы. Вместо того, чтобы снова использовать все методы IRepository, я унаследовал от класса GenericRepository.Общий репозиторий с UnitOfWork с пользовательскими методами IoC
Вот моя реализация UnitOfWork:
public interface IUnitOfWork<T> : IDisposable where T : DbContext
{
int Save();
T Context { get; }
}
public class UnitOfWork<T> : IUnitOfWork<T> where T : MyContext, new()
{
private readonly T _context;
public UnitOfWork()
{
_context = new T();
}
public UnitOfWork(T Context)
{
_context = Context;
}
public int Save()
{
return _context.SaveChanges();
}
public T Context
{
get
{
return _context;
}
}
public void Dispose()
{
_context.Dispose();
}
}
Это мой Repository реализация:
public interface IGenericRepository
{
IQueryable<T> All<T>() where T : class;
void Remove<T>(int id)where T : class;
void Remove<T>(T entity) where T : class;
void RemoveRange<T>(IList<T> entities) where T : class;
T Find<T>(int id) where T : class;
void Add<T>(T entity) where T : class;
void AddRange<T>(IList<T> entities) where T : class;
void Update<T>(T entity) where T : class;
int SaveChanges();
}
public class GenericRepository<C> : IGenericRepository where C : MyContext
{
protected readonly C _context;
public GenericRepository(IUnitOfWork<C> unitOfWork)
{
_context = unitOfWork.Context;
}
public int SaveChanges()
{
return _context.SaveChanges();
}
public IQueryable<T> All<T>() where T : class
{
return _context.Set<T>();
}
public void Remove<T>(int id) where T : class
{
T entity = _context.Set<T>().Find(id);
if (entity != null)
{
_context.Set<T>().Remove(entity);
}
}
public void Remove<T>(T entity) where T : class
{
if (entity != null)
{
_context.Set<T>().Remove(entity);
}
}
public void RemoveRange<T>(IList<T> entities) where T : class
{
if (entities.Count > 0)
{
_context.Set<T>().RemoveRange(entities);
}
}
public T Find<T>(int id) where T : class
{
return _context.Set<T>().Find(id);
}
public void Add<T>(T entity) where T : class
{
_context.Set<T>().Add(entity);
}
public void AddRange<T>(IList<T> entities) where T : class
{
_context.Set<T>().AddRange(entities);
}
public void Update<T>(T entity) where T : class
{
_context.Set<T>().Attach(entity);
_context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}
}
Вот пример Custom-Repository:
public interface IUserAccountRepository : IGenericRepository
{
UserAccount Find(string email, string password);
bool CheckDuplicate(string email);
}
public class UserAccountRepository<C> : GenericRepository<C> where C : CSharpAssigmentContext, IUserAccountRepository
{
protected readonly C _context;
public UserAccountRepository(IUnitOfWork<C> unitOfWork)
{
_context = unitOfWork.Context;
}
public int SaveChanges()
{
return _context.SaveChanges();
}
/// <summary>
/// Find user by email and password
/// </summary>
public UserAccount Find(string email, string password)
{
return _context.Set<UserAccount>().Where(ua => ua.Email == email && ua.Password == password).FirstOrDefault(null);
}
/// <summary>
/// Check wether user exists or not
/// </summary>
public bool CheckDuplicate(string email)
{
return _context.Set<UserAccount>().Any(ua => ua.Email == email);
}
public IQueryable<T> All<T>() where T : class
{
return _context.Set<T>();
}
public void Remove<T>(int id) where T : class
{
T entity = _context.Set<T>().Find(id);
if (entity != null)
{
_context.Set<T>().Remove(entity);
}
}
public void Remove<T>(T entity) where T : class
{
if (entity != null)
{
_context.Set<T>().Remove(entity);
}
}
public void RemoveRange<T>(IList<T> entities) where T : class
{
if (entities.Count > 0)
{
_context.Set<T>().RemoveRange(entities);
}
}
public T Find<T>(int id) where T : class
{
return _context.Set<T>().Find(id);
}
public void Add<T>(T entity) where T : class
{
_context.Set<T>().Add(entity);
}
public void AddRange<T>(IList<T> entities) where T : class
{
_context.Set<T>().AddRange(entities);
}
public void Update<T>(T entity) where T : class
{
_context.Set<T>().Attach(entity);
_context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}
Вот мое единство IoC код:
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
//UnitOfWork and GenericRepository
container.RegisterType(typeof(IUnitOfWork<CSharpAssigmentContext>),typeof(UnitOfWork<CSharpAssigmentContext>), new HierarchicalLifetimeManager());
container.RegisterType(typeof(IGenericRepository), typeof(GenericRepository<CSharpAssigmentContext>), new HierarchicalLifetimeManager());
//I keep receiving compile ERROR here
container.RegisterType(typeof(IUserAccountRepository), typeof(UserAccountRepository<CSharpAssigmentContext>), new HierarchicalLifetimeManager());
//Services
container.RegisterType(typeof(IUsersAccountsService), typeof(UsersAccountsService), new TransientLifetimeManager());
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
Как уже упоминалось в коде, я получаю ошибку во время компиляции для следующего кода:
container.RegisterType(typeof(IUserAccountRepository), typeof(UserAccountRepository<CSharpAssigmentContext>), new HierarchicalLifetimeManager());
Ошибка:
Тип MyContext не может быть использован в качестве типа параметр C в общем типе или методе. Не происходит никакого преобразования ссылок из MyContext в IMyClassRepository.
Как решить эту ошибку? Является ли моя реализация правильной для пользовательских репозиториев?
Можете ли вы показать свою подпись класса UserAccountRepository? –