我的应用程序使用“SignalR”客户端/服务器通信框架。如果您不熟悉,服务器端应用程序通常包含一个或多个“中心”类(类似于 asmx Web 服务),每个类都提供可由客户端调用的方法。在启动过程中,客户端需要首先创建连接,然后为需要与之通信的每个集线器创建一个“代理”,例如:-
var hubConnection = new HubConnection("http://...");
var fooHubProxy = hubConnection.CreateHubProxy("FooHub");
var barHubProxy = hubConnection.CreateHubProxy("BarHub");
...etc...
Run Code Online (Sandbox Code Playgroud)
传递给的字符串参数CreateHubProxy()是服务器端集线器类的名称。方法返回类型为IHubProxy.
感觉我应该能够在这里利用温莎,但我正在努力寻找解决方案。我的第一个想法是实例化集线器代理并向 Windsor 注册这些实例(按名称),例如
var fooHubProxy = hubConnection.CreateHubProxy("FooHub");
container.Register(Component.For<IHubProxy>().Instance(fooHubProxy).LifestyleSingleton().Named("FooHub"));
...etc...
Run Code Online (Sandbox Code Playgroud)
问题是,当一个类需要中心代理时,通过名称解析它的唯一方法是使用服务定位器模式,但不建议这样做。还有哪些其他 Windsor 功能(例如类型化工厂等)在这里可能有用?
编辑
我刚刚找到 Windsor's .UsingFactoryMethod,想知道这是否可行,以简化集线器注册:
container.Register(Component.For<IHubProxy>()
.UsingFactoryMethod((kernel, context) => hubConnection.CreateHubProxy("FooHub"))
.LifestyleSingleton()
.Named("FooHub"));
Run Code Online (Sandbox Code Playgroud)
我想我仍然有如何通过名称解决的问题。
小智 5
两年后,我为其他也遇到这个问题的人提供了一个更优雅的解决方案。可以使用 TypedFactory 工具并根据您的需要进行调整,如下所示。首先创建工厂接口(仅!不需要实际实现,castle 会处理这个):
public interface IHubProxyFactory
{
IHubProxy GetProxy(string proxyName);
}
Run Code Online (Sandbox Code Playgroud)
现在我们需要一个类来扩展默认类型化工厂并从输入 ( ) 中检索组件的名称proxyName:
class NamedTypeFactory : DefaultTypedFactoryComponentSelector
{
protected override string GetComponentName(MethodInfo method, object[] arguments)
{
string componentName = null;
if (arguments!= null && arguments.Length > 0)
{
componentName = arguments[0] as string;
}
if (string.IsNullOrEmpty(componentName))
componentName = base.GetComponentName(method, arguments);
return componentName;
}
}
Run Code Online (Sandbox Code Playgroud)
然后向 castle 注册工厂并指定将使用您的 NamedTypeFactory:
Component.For<IHubProxyFactory>().AsFactory(new NamedTypeFactory())
Run Code Online (Sandbox Code Playgroud)
现在每个类都可以在其构造函数中获取工厂接口:
public class SomeClass
{
private IHubProxy _fooHub;
private IHubProxy _barHub;
public SomeClass(IHubProxyFactory hubProxyFactory)
{
_fooHub = hubProxyFactory.GetProxy("FooHub");
_barHub = hubProxyFactory.GetProxy("BarHub");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6231 次 |
| 最近记录: |