gpt4 book ai didi

c# - 可能的 GetObjectsOfType 替换

转载 作者:太空宇宙 更新时间:2023-11-03 22:16:21 25 4
gpt4 key购买 nike

我有这么一小段代码

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 的引用。

关于c# - 可能的 GetObjectsOfType 替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5026711/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com