我在我的项目中使用 UnitOfWork 和 Repository 模式。我正在尝试编写干净的代码。
这是我的 IUnitOfWork.cs (应用层)
public interface IUnitOfWork : IDisposable
{
int Save();
IGenericRepository<TEntity> Repository<TEntity>() where TEntity : class;
}
执行 UnitOfWork.cs :(持久层)
public class UnitOfWork : IUnitOfWork
{
private readonly DBContext _context;
private Hashtable _repositories;
public UnitOfWork(DBContext context)
{
_context = context;
}
public IGenericRepository<T> Repository<T>() where T : class
{
if (_repositories == null)
_repositories = new Hashtable();
var type = typeof(T).Name;
if (!_repositories.ContainsKey(type))
{
var repositoryType = typeof(GenericRepository<>);
var repositoryInstance =
Activator.CreateInstance(repositoryType
.MakeGenericType(typeof(T)), _context);
_repositories.Add(type, repositoryInstance);
}
return (IGenericRepository<T>)_repositories[type];
}
public int Save()
{
// Save changes with the default options
return _context.SaveChanges();
}
// etc.. Dispose()
}
我的 IGenericRepository.cs : (应用层)
public interface IGenericRepository<TEntity>
where TEntity : class
{
void Update(TEntity entity);
void Delete(object id);
void InsertList(IEnumerable<TEntity> entities);
// etc..
}
在我的服务中:(应用层)
var result = UnitOfWork.Repository<Entities.Example>().Delete(id);
并使用 Unity,我将依赖项注入(inject)容器中。
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager())
它就像一个魅力。
现在我有一个自定义存储库
ICustomRepository
:public interface ICustomRepository: IGenericRepository<Entities.Custom>
{
void Test();
}
如何访问
Test()
函数使用我的 IUnitOfWork
?var result = UnitOfWork.Repository<Entities.Custom>().Test(); // not working
更新 :
@Thomas Cook 给了我一种使用 cast 的方法:
(UnitOfWork.Repository<Entities.Custom>() as ICustomRepository).Test();
我得到一个 NullReferenceException:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
最佳答案
你必须转换,因为 UnitOfWork
Repository
方法返回 IGenericRepository
没有声明 Test
.因此,您需要将返回值转换为 ICustomRepository
继承IGenericRepository
和 Test
上的 bolt 方法。
关于c# - UnitOfWork & Generic Repository,带有自定义存储库的 SOLID 原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62263566/