我有一个像“消息总线”一样的系统
interface IMessageHandler<T> {
void Handle(T message);
}
class MessageBus {
private readonly Dictionary<Type, Action<object>> _handlers = new Dictionary<Type, Action<object>>();
void AddHandler<T>(IMessageHandler<T> handler) {
_messageHandlers[typeof(T)] = message => messageHandler.Handle((T)message);
}
public void Handle(object message)
{
_handlers[message.GetType()](message);
}
}
但不是直接传递消息处理程序的实例,我想传递一个 Func,以执行延迟加载方法(仅在第一次请求时实例化消息处理程序。然后如果我有 1000 个消息处理程序,并且在一个执行我只使用 5,我可以避免实例化另一个 995)
我目前完成它的方法(省略了包含定义+实例的列表并检查实例是否已经解析等的所有部分),
是在Handle
调用它:
var messageType = message.GetType();
var definition = _definitions[messageType];
var instance = definition();
var handleMethod = instance.GetType().GetMethod("Handle");
handleMethod.Invoke(new [] {message});
但是性能会很差,有没有其他更好的方法?
谢谢
您可以使用Dictionary<Type, Lazy<Action<object>>>
代替Dictionary<Type, Action<object>>
,因此处理程序的实例将仅创建一次并且仅在必要时创建。
class MessageBus
{
private readonly Dictionary<Type, Lazy<Action<object>>> _handlers = new Dictionary<Type, Lazy<Action<object>>>();
public void AddHandler<T>(Func<IMessageHandler<T>> handlerFactory)
{
Func<Action<object>> objectHandlerFactory = CreateObjectHandlerFactory(handlerFactory);
_handlers[typeof(T)] = new Lazy<Action<object>>(objectHandlerFactory);
}
public void Handle(object message)
{
_handlers[message.GetType()].Value(message);
}
private Func<Action<object>> CreateObjectHandlerFactory<T>(Func<IMessageHandler<T>> handlerFactory)
{
return () =>
{
var handler = handlerFactory();
return message => handler.Handle((T)message);
};
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句