Question

I have written a small pub / sub system for our app,

you subscribe to messages by implementing IHandle

Lets say the subscriber implements IHandle<IEnumerable<MyType>>

Then someone publish a message of type ICollection<MyType>> this should off course trigger the subscriber since a IColletion<> is of Type IEnumerable<>

But my code does not support this, a work around is that the publisher casts the ICollection to a IEnumerable but its prone to bugs in a larger team.

This is the code that does not work

public void Publish<T>(T message) where T : class
{
    if (config.EnableEventAggregator)
        subscribers.OfType<IHandle<T>>()
        .ForEach(s => s.Handle(message));
}

I want it to find the IHandle<IEnumerable> for all types that inherit IEnumerable<T> Any ideas?

Was it helpful?

Solution

You need to define IHandle as contra-variant so that you don't need to work around:

interface IHandle<in T>

With this way it will accept all types which inherits from IEnumerable

This link is explained for you in detail how covariance and contra-variance work with genric

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top