如何构建需要多个存储库的服务?

时间:2016-11-28 17:54:10

标签: entity-framework unit-testing mocking repository-pattern

我有一个使用2个存储库的服务,我想进行单元测试。所以对于测试我需要让构造函数直接接受接口而不是存储库类,所以我可以模拟存储库。但是我不能将他们的DbContext设置为相同的,这将导致其他问题。

以下是代码:

public class RolePrivilegeService : IRolePrivilegeService
{
    private readonly RoleReadWriteRepository _roleRepo;
    private readonly PrivilegeReadRepository _privilegeRead;

    public RolePrivilegeService(RoleReadWriteRepository roleWrite, 
        PrivilegeReadRepository privilegeRead)
    {
        _roleRepo = roleWrite;
        _privilegeRead = privilegeRead;

        _roleRepo.Db = _privilegeRead.Db;
    }

    public async Task<int> AssignPrivilege(string roleId, string privilegeId, string companyId)
    {
        var role = await _roleRepo.FindRole(companyId, roleId);
        if(role == null) throw new RoleNotFoundException();

        var privilege = await _privilegeRead.Find(privilegeId);
        if(privilege == null) throw new PrivilegeNotFoundException();

        role.AssignPrivilege(privilege);

        return await _roleRepo.UpdateRole(role);
    }
}

接口和实体位于一个项目中,服务和存储库位于另一个项目中。

1 个答案:

答案 0 :(得分:1)

我想从一开始就认为,给服务部门管理上下文的独特性不是最好的解决方案。

一些可能的解决方案(我最喜欢的是第三个)

1)使用接口代替并注入DBContext(在此定义您的策略,如果您在api或其他任何地方,请求一个DBContext)。

2)无论如何,您可以使用NSubstitute或其他人嘲笑具体课程

3)通过使用一个存储库来改进您的设计,以便更好地抽象所需的实体(使用聚合,这是对事务边界的更好抽象)