问题描述
我有这个 wcf 方法
I have this wcf method
Profile GetProfileInfo(string profileType, string profileName)
和业务规则:
如果 profileType 是从数据库中读取的A".
if profileType is "A" read from database.
如果 profileType 是从 xml 文件中读取的B".
if profileType is "B" read from xml file.
问题是:如何使用依赖注入容器来实现?
The question is: how to implement it using a dependency injection container?
推荐答案
让我们首先假设您有一个 IProfileRepository,如下所示:
Let's first assume that you have an IProfileRepository something like this:
public interface IProfileRepository
{
Profile GetProfile(string profileName);
}
以及两个实现:DatabaseProfileRepository
和 XmlProfileRepository
.问题是您想根据 profileType 的值选择正确的.
as well as two implementations: DatabaseProfileRepository
and XmlProfileRepository
. The issue is that you would like to pick the correct one based on the value of profileType.
你可以通过引入这个抽象工厂来做到这一点:
You can do this by introducing this Abstract Factory:
public interface IProfileRepositoryFactory
{
IProfileRepository Create(string profileType);
}
假设 IProfileRepositoryFactory 已经被注入到服务实现中,你现在可以像这样实现 GetProfileInfo 方法:
Assuming that the IProfileRepositoryFactory has been injected into the service implementation, you can now implement the GetProfileInfo method like this:
public Profile GetProfileInfo(string profileType, string profileName)
{
return this.factory.Create(profileType).GetProfile(profileName);
}
IProfileRepositoryFactory 的具体实现可能如下所示:
A concrete implementation of IProfileRepositoryFactory might look like this:
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 来为您连接所有...
Now you just need to get your DI Container of choice to wire it all up for you...
这篇关于WCF 依赖注入和抽象工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!