Click here to Skip to main content
15,070,111 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello!

I have a scenario as follows:
C#
public class Envelope
{

public string MessageId {get;}

public abstract Stream GetStream() 

}


C#
public class Envelope<T> : Envelope
{
public T Body {get;}
}


I have another 2 classes called MessageBus and MessageSender that is responsible to manage and transmit the message to entire application services.

C#
public class MessageBus
{

public void Send(Envelope message)
{
sender.Dispatch(message);
}

}

public class MessageSender
{

public void Dispatch(Envelope message)
{

// THE PROBLEM IS HERE!!!!!
// HOW DO I IDENTIFY THE TYPE OF BODY? 
// On Envelope (base class) the property Body is missing and i can't get the type 
// to try create instance of change type .. and i need to pass body as parameter to 
// another method
}
}


Sorry for my bad english and thank you very much for your time :)

What I have tried:

Reflection can be work, but i trying to solve it with a more 'elegant' way.
Posted
Updated 22-Jul-16 3:47am

Quote:
and i need to pass body as parameter to another method
That other method needs to be generic, too; or at least accept a type compatible with T. Otherwise, the encapsulation in the generic class does not make sense.
   
You should probably add the following function to your Envelope class:
C#
public abstract Type GetBodyType();


And then implement it in the derived class Envelope<T>:
C#
return typeof(T);


Or maybe you need to reconsider the whole design... Are you trying to convert a pattern from another language?
   
What is the benefit of generics here? These can be overused and then you get into situations like this. Can you not just stick the body in the non-generic Envelope as type object?

Moreover, presuming some sort of serialization will be required in order to dispatch this thing on a message bus, perhaps there is a base interface or something you can use as the type of Body?
   
Check this link. Hope it gives you a clue.

c# - How to get the type of T from a generic List - Stack Overflow[^]
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900