【发布时间】:2018-08-06 06:55:10
【问题描述】:
我使用代理和拦截来记录日志。我要记录的属性之一是来自 rabbit MQ 的消息 ID。
我们正在使用以下对象:
namespace MassTransit
{
public interface ConsumeContext<out T> : ConsumeContext, MessageContext, PipeContext, IPublishEndpoint, IPublishObserverConnector, ISendEndpointProvider where T : class
{
T Message { get; }
/// <summary>Notify that the message has been consumed</summary>
/// <param name="duration"></param>
/// <param name="consumerType">The consumer type</param>
Task NotifyConsumed(TimeSpan duration, string consumerType);
/// <summary>
/// Notify that a fault occurred during message consumption
/// </summary>
/// <param name="duration"></param>
/// <param name="consumerType"></param>
/// <param name="exception"></param>
Task NotifyFaulted(TimeSpan duration, string consumerType, Exception exception);
}
}
这是我需要在拦截中掌握的通用消息。
我可以成功地将它投射到一个对象上说:
ConsumeContext<AuthenticationDataRequest>
在 Visual Studio 中,一旦我投射了它,Message 对象就会弹出(没有投射就没有 MessageObject)。
要转换,我使用以下通用方法:
public Guid? RunMessageRetrieve(dynamic obj, Type castTo)
{
MethodInfo castMethod = GetType().GetMethod("GetMessageIdFromContext").MakeGenericMethod(castTo);
return castMethod.Invoke(null, new object[] { obj }) as Guid?;
}
public static Guid? GetMessageIdFromContext<T>(dynamic context) where T : class
{
Guid? messageId = null;
try
{
var contextCasted = (T)context;
Type contextType = contextCasted.GetType();
var message = contextCasted.GetType().GetProperty("Message");
if (message != null)
{
messageId = message.GetType().GetProperty("MessageId").GetValue(message) as Guid?;
}
}
catch (InvalidCastException castException)
{
Console.WriteLine("Could not retrieve message Id from context message as the cast failed");
}
catch (NullException nullException)
{
Console.WriteLine("Could not retrieve message Id from context as the message Id did not exist");
}
return messageId;
}
在这里您可以在 Visual Studio 中看到消息,在其中我可以获取消息 ID:
但是,我尝试使用反射来获取实际的消息属性,因为我当然不知道编译时的类型,而且我似乎无法解决它。以下为空,因为它当然是泛型类型:
var message = contextCasted.GetType().GetProperty("Message");
这必须是可行的,因为在拦截后调用实际方法时,它具有带有消息的正确对象。
【问题讨论】:
标签: c# generics casting castle-dynamicproxy