WCF依赖注入和抽象工厂

前端之家收集整理的这篇文章主要介绍了WCF依赖注入和抽象工厂前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个wcf方法
  1. Profile GetProfileInfo(string profileType,string profileName)

和业务规则:

如果profileType是从数据库读取的“A”。

如果profileType是从xml文件读取的“B”。

问题是:如何使用依赖注入容器来实现?

我们首先假设你有一个这样的IProfileRepository:
  1. public interface IProfileRepository
  2. {
  3. Profile GetProfile(string profileName);
  4. }

以及两个实现:DatabaseProfileRepository和XmlProfileRepository。问题是您希望根据profileType的值选择正确的。

您可以通过介绍这个抽象工厂来做到这一点:

  1. public interface IProfileRepositoryFactory
  2. {
  3. IProfileRepository Create(string profileType);
  4. }

假设IProfileRepositoryFactory已被注入到服务实现中,现在可以实现GetProfileInfo方法,如下所示:

  1. public Profile GetProfileInfo(string profileType,string profileName)
  2. {
  3. return this.factory.Create(profileType).GetProfile(profileName);
  4. }

IProfileRepositoryFactory的具体实现可能如下所示:

  1. public class ProfileRepositoryFactory : IProfileRepositoryFactory
  2. {
  3. private readonly IProfileRepository aRepository;
  4. private readonly IProfileRepository bRepository;
  5.  
  6. public ProfileRepositoryFactory(IProfileRepository aRepository,IProfileRepository bRepository)
  7. {
  8. if(aRepository == null)
  9. {
  10. throw new ArgumentNullException("aRepository");
  11. }
  12. if(bRepository == null)
  13. {
  14. throw new ArgumentNullException("bRepository");
  15. }
  16.  
  17. this.aRepository = aRepository;
  18. this.bRepository = bRepository;
  19. }
  20.  
  21. public IProfileRepository Create(string profileType)
  22. {
  23. if(profileType == "A")
  24. {
  25. return this.aRepository;
  26. }
  27. if(profileType == "B")
  28. {
  29. return this.bRepository;
  30. }
  31.  
  32. // and so on...
  33. }
  34. }

现在你只需要让你的DI容器选择将其全部连接起来…

猜你在找的设计模式相关文章