我有这小段代码
var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
.GetObjectsOfType(typeof (ICustomInterfaceThatDoesSomething));
foreach (ICustomInterfaceThatDoesSomething icitds in idObjects.Values)
icitds.DoSomething();
有没有一种方法可以让spring.net自动将单例注入我声明的属性(例如
ICustomInterfaceThatDoesSomething
的数组)来避免这种情况?我想要这样的唯一原因是因为我想杀死项目上的.dll依赖项,这是单点使用。
最佳答案
您也可以使用method injection:
在sharedLib中:
public class MyService
{
public void ProcessAll()
{
foreach (ICustomInterfaceThatDoesSomething icitds in GetAllImplementers())
icitds.DoSomething();
}
protected virtual IEnumerable<ICustomInterfaceThatDoesSomething> GetAllImplementers()
{
// note that the Spring dependency is gone
// you can also make this method abstract,
// or create a more useful default implementation
return new List<ICustomInterfaceThatDoesSomething>();
}
}
在网络应用中,添加一个实现
GetAllImplementers()
的类:public class ServiceLocatorImplementer : IMethodReplacer
{
protected IEnumerable<ICustomInterfaceThatDoesSomething> GetAllImplementers()
{
var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
.GetObjectsOfType(typeof(ICustomInterfaceThatDoesSomething));
return idObjects.Values.Cast<ICustomInterfaceThatDoesSomething>();
}
public object Implement(object target, MethodInfo method, object[] arguments)
{
return GetAllImplementers();
}
}
并在Web应用程序的对象定义中配置方法注入:
<objects>
<object name="serviceLocator"
type="WebApp.ServiceLocatorImplementer, WebApp" />
<object name="service" type="SharedLib.MyService, SharedLib">
<replaced-method name="GetAllImplementers" replacer="serviceLocator" />
</object>
</objects>
我确实认为使用
CommonServiceLocator
会更好(因为服务位置就是您正在做的事情),但是以这种方式使用方法注入,您不需要引入对SharedLib
的其他引用。关于c# - 可能的GetObjectsOfType替换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5026711/