有兩種方式來獲得運行時類型:傳遞消息作爲一個參數或使用反射。
修改方法:
public static IMessageHandler<T> Resolve<T>(T unused)
{
return _container.Resolve<IMessageHandler<T>>();
}
,這將允許運行時類型查找:
// Cast to dynamic to force runtime type
messageHandler = AppContainerInstaller.Resolve((dynamic) message);
您也可以使用反射雖然有性能損失。
private static readonly MethodInfo ResolveMethodInfo
= typeof(AppContainerInstaller).GetMethod("Resolve", BindingFlags.Public | BindingFlags.Static);
// Assuming there exists a non-generic interface IMessageHandler
private readonly ConcurrentDictionary<Type, Func<IMessageHandler>> _methodCache
= new ConcurrentDictionary<Type, Func<IMessageHandler>>();
public static string ProcessMessage(IMessage message)
{
messageHandler = Resolve(message.GetType());
return messageHandler.Handle(message);
}
private IMessageHandler Resolve(Type type)
{
// Cache the generated method to avoid repeated reflection penalty.
var resolve = _methodCache.GetOrAdd(type,() => ResolveMethodInfo.MakeGenericMethod(type));
return resolve();
}
通用類型需要在編譯時已知(Resolve)。 –
Dunken