我有这个wcf方法
- Profile GetProfileInfo(string profileType,string profileName)
和业务规则:
如果profileType是从数据库读取的“A”。
如果profileType是从xml文件读取的“B”。
问题是:如何使用依赖注入容器来实现?
我们首先假设你有一个这样的IProfileRepository:
- public interface IProfileRepository
- {
- Profile GetProfile(string profileName);
- }
以及两个实现:DatabaseProfileRepository和XmlProfileRepository。问题是您希望根据profileType的值选择正确的。
您可以通过介绍这个抽象工厂来做到这一点:
- public interface IProfileRepositoryFactory
- {
- IProfileRepository Create(string profileType);
- }
假设IProfileRepositoryFactory已被注入到服务实现中,现在可以实现GetProfileInfo方法,如下所示:
- public Profile GetProfileInfo(string profileType,string profileName)
- {
- return this.factory.Create(profileType).GetProfile(profileName);
- }
IProfileRepositoryFactory的具体实现可能如下所示:
- public class ProfileRepositoryFactory : IProfileRepositoryFactory
- {
- private readonly IProfileRepository aRepository;
- private readonly IProfileRepository bRepository;
- public ProfileRepositoryFactory(IProfileRepository aRepository,IProfileRepository bRepository)
- {
- if(aRepository == null)
- {
- throw new ArgumentNullException("aRepository");
- }
- if(bRepository == null)
- {
- throw new ArgumentNullException("bRepository");
- }
- this.aRepository = aRepository;
- this.bRepository = bRepository;
- }
- public IProfileRepository Create(string profileType)
- {
- if(profileType == "A")
- {
- return this.aRepository;
- }
- if(profileType == "B")
- {
- return this.bRepository;
- }
- // and so on...
- }
- }
现在你只需要让你的DI容器选择将其全部连接起来…