c# - UnitOfWork & Generic Repository,带有自定义存储库的 SOLID 原则

标签 c# dependency-injection repository-pattern unit-of-work solid-principles

我在我的项目中使用 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继承IGenericRepositoryTest 上的 bolt 方法。

关于c# - UnitOfWork & Generic Repository,带有自定义存储库的 SOLID 原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62263566/

相关文章:

c# - 调用 Task.Result 时 Windows 窗体中断

c# - 为什么 ref 和 out 不足以消除 C# 中重载的歧义?

c# - 简单的线程编程

Android 存储库模式将 room 转换为域模型

asp.net-mvc - ASP.NET MVC服务层输入输出数据

c# - MySQL56 - 加载数据本地 INFILE - {"Parameter ' @url_hash' 必须定义。"} c#

c# - 如何正确使用依赖注入(inject)?

scala - ( Play 2.4)特征中的依赖注入(inject)?

php - Zend Framework 中的DI 2. 如何建立循环依赖?

asp.net - 存储库模式最佳实践