WCF依赖注入和抽象工厂

我有这个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容器选择将其全部连接起来…

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...