19

我有这个 wcf 方法

Profile GetProfileInfo(string profileType, string profileName)

和业务规则:

如果 profileType 是“A”,则从数据库中读取。

如果 profileType 为“B”,则从 xml 文件中读取。

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

4

2 回答 2

24

我们首先假设您有一个类似这样的 IProfileRepository:

public interface IProfileRepository
{
     Profile GetProfile(string profileName);
}

以及两个实现:DatabaseProfileRepositoryXmlProfileRepository. 问题是您想根据 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 Container 来为您连接起来...

于 2010-01-30T18:18:36.400 回答
6

马克的回答很好,但是给出的解决方案不是抽象工厂,而是标准工厂模式的实现。请检查 Marks 类如何适合标准工厂模式 UML 图。单击此处查看应用于工厂模式 UML 的上述类

由于在工厂模式中,工厂知道具体的类,我们可以使代码ProfileRepositoryFactory更简单,如下所示。将不同的存储库注入工厂的问题在于,每次添加新的具体类型时,您都会有更多的代码更改。使用以下代码,您只需更新开关以包含新的具体类


    public class ProfileRepositoryFactory : IProfileRepositoryFactory
    {
        public IProfileRepository Create(string profileType)
        {
            switch(profileType)
            {
                case "A":
                    return new DatabaseProfileRepository(); 

                case  "B":
                    return new XmlProfileRepository();
            }
        }
    }

抽象工厂是一种更高级的模式,用于创建相关或依赖对象的系列,而无需指定它们的具体类。这里提供的 UML 类图很好地解释了它。

于 2016-04-08T12:00:06.647 回答