NServiceBus Create Message has counter intutive concrete type implementation requiring cumbersome casts of type
NServiceBus creates concrete implementation classes from interfaces to uses as messages. This is in theory to allow for the composition of these messages from other messages. In effect allowing for multiple inheritance. To demonstrate the inconsistent behavior I created a few test interfaces:
public interface ITestBase1
{
string Property1 { get; set; }
}
public interface ITestBase2 : ITestBase1
{
}
public interface ITestBase3 : ITestBase2
{
}
I then ran the following code:
var types = new[] { typeof(ITestBase1) };
new NServiceBus.MessageInterfaces.MessageMapper.Reflection.MessageMapper().Initialize(types);
var msg = new NServiceBus.MessageInterfaces.MessageMapper.Reflection.MessageMapper().CreateInstance(typeof(ITestBase1));
If I create concrete implementation of ITestBase1 I find exactly what I would expect. One Property called Property1. If I create concrete implementation of ITestBase2, I find msg has one Property1 property.
If I create concrete implementation of ITestBa开发者_JAVA百科se3, however, I get two implementation of Property1 on the msg object. One for the ITestBase1 and one for the ITestBase2 interfaces. This seems a bit counter intuitive to me. I would expect the number of Property1 implementations on the base message to not vary. This makes it quite confusing when trying to build messages out of components.
Short of modifying the messagemapper.GetAllProperties code of nservicebus is there a way around this behavior? I would rather not have the other interfaces create new properties of the same datatype and name.
My understanding of the purpose of the concrete implementations is:
- so that no implementation is required in the subscribing service, and
to enable convenience creation of simple messages, eg:
Bus.Publish<IMyMessage>(m => { m.Property1 = "My Value"; });
I'm struggling to envisage a scenario where you'd need to create your own instances directly. Can you elaborate on what you're doing here?
This may be a VS bug. I have a hierarchy as follows: IProductCreatedEvent : IProductChangedEvent: IEvent: IMessage. Using your code I see in the VS debugger the behaviour you describe:
But if you reflect on the type, the properties show correctly:
If I cast to IEvent and set properties everything works as expected. So the runtime is viewing the type correctly despite what the debugger is showing so you should be ok to continue to model your messages this way.
精彩评论