Dependency injection Spring.net IoC-各州不同级别

Dependency injection Spring.net IoC-各州不同级别,dependency-injection,spring.net,Dependency Injection,Spring.net,我正在尝试注入一个依赖项,该依赖项随传入的状态而变化。例如,如果州是威斯康星州,我想注入一个类,但如果是伊利诺伊州,我想注入另一个类。这不是一对一,而是7个州代表一个州,3个州代表另一个州 在Spring.net中有没有一种方法可以在配置xml中检查一系列值?这是本书第6.1章“将运行时值映射到抽象”的主题。建议的解决方案是使用抽象工厂。您的抽象工厂可能如下所示: public interface IStateAlgorithmFactory { IStateAlgorithm Crea

我正在尝试注入一个依赖项,该依赖项随传入的状态而变化。例如,如果州是威斯康星州,我想注入一个类,但如果是伊利诺伊州,我想注入另一个类。这不是一对一,而是7个州代表一个州,3个州代表另一个州


在Spring.net中有没有一种方法可以在配置xml中检查一系列值?

这是本书第6.1章“将运行时值映射到抽象”的主题。建议的解决方案是使用
抽象工厂
。您的抽象工厂可能如下所示:

public interface IStateAlgorithmFactory
{
    IStateAlgorithm Create(string state);
}
并将此工厂注入到您知道要处理哪个状态的消费者身上。要获得一个
IStateAlgorithm
他的消费者然后调用y

alg = _factory.Create("Illnois");
或者,如果需要完全配置控制,您可以创建一个简单的工厂,将状态名称映射到spring容器管理的实例

简单例子 我想您有几个类实现了某个
IStateAlgorithm

公共接口算法
{
字符串ProcessState(字符串stateName);
}
公共类EchoingState算法:IStatalgorithm
{
公共字符串ProcessState(字符串stateName)
{
返回stateName;
}
}
公共类反向选择状态算法:IStateAlgorithm
{
公共字符串ProcessState(字符串stateName)
{
返回新字符串(stateName.Reverse().ToArray());
}
}
还有一个特定的
消费者
,需要根据运行时值选择算法。消费者可以被注入一个工厂,从中可以检索其所需的算法:

公共类消费者
{
私有只读IStateAlgorithFactory\u工厂;
公共消费者(IStateAlgorithFactory)
{
_工厂=工厂;
}
公共字符串进程(字符串状态)
{
var alg=_factory.Create(state);
返回alg.ProcessState(状态);
}
}
一个简单的工厂实现只需打开状态值、使用if或查找内部列表:

公共接口ISTALGorithFactory
{
IStateAlgorithm创建(字符串状态);
}
公共类StateAlgorithFactory:IStateAlgorithFactory
{
私有字符串[]_reverseStates=新[]{“威斯康星州”、“阿拉斯加”};
公共IStateAlgorithm创建(字符串状态)
{
如果(_reversestes.Contains(state))
返回新的反向选择状态算法();
返回新的EchoingStateAlgorithm();
}
}
Net可配置示例 如果希望能够在spring配置中配置
IStateAlgorithm
,可以引入
lookupstateAlgorithFactory
。本例假设您的
IStateAlgorithm
s是无状态的,可以在使用者之间共享:

公共类LookupStateAlgorithFactory:IStateAlgorithFactory
{
私有只读IDictionary_stateToAlgorithmap;
私有只读IStateAlgorithm\u defaultAlgorithm;
public LookupStateAlgorithmFactory(IDictionary stateToAlgorithmMap,
IStateAlgorithm(默认算法)
{
_stateToAlgorithmMap=stateToAlgorithmMap;
_defaultAlgorithm=defaultAlgorithm;
}
公共IStateAlgorithm创建(字符串状态)
{
ISTATEALG算法;
if(!\u stateToAlgorithmMap.TryGetValue(state,out alg))
alg=_默认算法;
返回alg;
}
}
xml配置可以是:



正如您已经提到的,依赖于
iaapplicationContextAware
是一件坏事。如果
EchoingStateAlgorization
ReverseeChoingStateAlgorization
是无状态的(imho他们应该是什么),并且cheep to build,则无需询问上下文。只需使用字典中的具体实现,例如
。这是一个很好的建议,如果它们是无状态的,您可以在查找工厂的使用者之间共享实例。实际上,在我的示例中,
StateAlgorithm
s是单例的,我可能也应该这样做。当您希望
lookupFactory
在每次调用
Create
时返回新实例并在xml配置中配置这些实例时,最清晰的方法是
iaapplicationContextAware
,IMO。我将在一秒钟内更新一个非常清晰的解决方案和一个非常详细的答案。谢谢分享。谢谢你这么棒的回答。我感谢你的帮助!