我有这个WCF方法
Profile GetProfileInfo(string profileType, string profileName)
还有一个业务规则:
如果profileType是“A”,则从数据库中读取。
如果profileType是“B”,则从xml文件中读取。
问题是:如何使用依赖注入容器实现它?
我有这个WCF方法
Profile GetProfileInfo(string profileType, string profileName)
还有一个业务规则:
如果profileType是“A”,则从数据库中读取。
如果profileType是“B”,则从xml文件中读取。
问题是:如何使用依赖注入容器实现它?
首先假设您拥有一个类似于以下内容的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...
}
}
现在你只需要选择你喜欢的依赖注入容器,让它为你连接所有内容...
ProfileRepositoryFactory
代码简化如下。注入不同的存储库到工厂的问题在于每次添加新的具体类型时您需要进行更多的代码更改。使用以下代码,您只需更新switch以包含新的具体类即可。
public class ProfileRepositoryFactory : IProfileRepositoryFactory
{
public IProfileRepository Create(string profileType)
{
switch(profileType)
{
case "A":
return new DatabaseProfileRepository();
case "B":
return new XmlProfileRepository();
}
}
}
抽象工厂是一种更高级的模式,用于创建相关或依赖对象族,而不指定它们的具体类。这里提供的UML类图 在此处 很好地解释了它。
ProfileRepositoryFactory
类放在哪个包中?是在组合根(它涉及对象创建),服务层(这是业务规则)还是实际存储库实现旁边? - MEMark