可能的 GetObjectsOfType 替换 [英] possible GetObjectsOfType replacement
问题描述
我有一小段代码
var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
.GetObjectsOfType(typeof (ICustomInterfaceThatDoesSomething));
foreach (ICustomInterfaceThatDoesSomething icitds in idObjects.Values)
icitds.DoSomething();
有没有办法通过让 spring.net 自动将单例注入我声明的属性来避免这种情况,例如 ICustomInterfaceThatDoesSomething
的数组?
Is there a way i can avoid this by having spring.net automatically inject the singletons to a property i declare, like an array of ICustomInterfaceThatDoesSomething
?
我想要这样的唯一原因是因为我想终止对项目的 .dll 依赖,这是单点使用.
The only reason i want something like this is because i want to kill the .dll dependency on the project and this is the single point of usage.
推荐答案
感谢 Marijin 的洞察力,这已经解决了!
thanx to Marijin's insight this has been nailed!
首先考虑这个通用的实用程序类
Firstly consider this all-purpose utility class
public class ServiceLocatorImplementer : IMethodReplacer
{
private readonly Type _forType;
public ServiceLocatorImplementer(Type forType)
{
this._forType = forType;
}
protected IEnumerable GetAllImplementers()
{
var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
.GetObjectsOfType(_forType);
return idObjects.Values;
}
public object Implement(object target, MethodInfo method, object[] arguments)
{
return GetAllImplementers();
}
}
用这个配置示例声明它
<object id="FindInterfaceUsages" type="ServiceLocatorImplementer, SpringDependendAssembly">
<constructor-arg name="forType">
<object type="System.Type" factory-method="GetType">
<constructor-arg type="string" name="typeName" value="Foo.Bar.IChe, NONSpringDependendAssembly" />
<!-- i use the strict overload -->
<constructor-arg type="bool" name="throwOnError" value="true" />
<constructor-arg type="bool" name="ignoreCase" value="false" />
</object>
</constructor-arg>
</object>
<object id="MightyPirate" type="Foo.Pirates, NONSpringDependendAssembly">
<replaced-method name="GetAllICheImplentations" replacer="FindInterfaceUsages" />
</object>
最后注入到所需的目标
这种方法的真正优点在于,在您实际执行 GetAllICheImplentations()
之前不会调用底层的 GetObjectsOfType(除非您尝试在spring init 这不是好兆头)
What is trully great with this methodology is that the underlying GetObjectsOfType is not going to be called until you actually execute GetAllICheImplentations()
(unless you try to execute it during spring init which is not going to bode well)
这篇关于可能的 GetObjectsOfType 替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!