DDD的工厂模式

时间:2016-08-17 06:35:58

标签: domain-driven-design factory-pattern

在DDD中使用工厂的正确或建议的方法是什么?

工厂方法应该从应用程序服务接收所有必要的参数,还是允许我们在工厂内注入存储库并提取所需的数据?

应该是(例1):

public class UserTokenFactory : IUserTokenFactory
    {
        IUserTypeResourceRepository _userTypeResourceRepository;
        public UserTokenFactory(IUserTypeResourceRepository userTypeResourceRepository)
        {
            _userTypeResourceRepository = userTypeResourceRepository;
        }

        public async Task<UserToken> CreateWithAsync(User user)
        {
            var userTypeResources = await _userTypeResourceRepository.GetByUserTypeIdAsync(user.UserTypeId);

            //Some logic for creating user tokens
            throw new NotImplementedException();
        }
    }

或(例2)

public class UserTokenFactory : IUserTokenFactory
    {
        IUserTypeResourceRepository _userTypeResourceRepository;
        public UserTokenFactory(IUserTypeResourceRepository userTypeResourceRepository)
        {
            _userTypeResourceRepository = userTypeResourceRepository;
        }

        public UserToken CreateWith(User user, List<UserTypeResource> userTypeResources)
        {
            //Some logic for creating user tokens
            throw new NotImplementedException();
        }
    }

1 个答案:

答案 0 :(得分:2)

您可以向工厂注入服务。您的工厂基本上是一个域服务,恰好创建对象。但是,我可能在这里依赖ISP并定义IResolveUserType之类的接口,而不是依赖于更广泛的IUserTypeResourceRepository接口。