我有这么一小段代码
var idObjects = Spring.Context.Support.ContextRegistry.GetContext()
.GetObjectsOfType(typeof (ICustomInterfaceThatDoesSomething));
foreach (ICustomInterfaceThatDoesSomething icitds in idObjects.Values)
icitds.DoSomething();
有没有办法让 spring.net 自动将单例注入(inject)我声明的属性,比如 ICustomInterfaceThatDoesSomething 数组?
我想要这样的东西的唯一原因是因为我想取消对项目的 .dll 依赖,这是单点使用。
请您参考如下方法:
你也可以使用 method injection :
在共享库中:
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 应用程序的对象定义中配置方法注入(inject):
<objects>
<object name="serviceLocator"
type="WebApp.ServiceLocatorImplementer, WebApp" />
<object name="service" type="SharedLib.MyService, SharedLib">
<replaced-method name="GetAllImplementers" replacer="serviceLocator" />
</object>
</objects>
我确实觉得使用 CommonServiceLocator 会更好(因为服务定位就是你正在做的),但是以这种方式使用方法注入(inject),你不需要引入额外的对 SharedLib 的引用。
