加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

WCF依赖注入和抽象工厂

发布时间:2020-12-14 04:30:16 所属栏目:百科 来源:网络整理
导读:我有这个wcf方法 Profile GetProfileInfo(string profileType,string profileName) 和业务规则: 如果profileType是从数据库读取的“A”。 如果profileType是从xml文件读取的“B”。 问题是:如何使用依赖注入容器来实现? 我们首先假设你有一个这样的IProfi
我有这个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容器选择将其全部连接起来…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读