Search code examples
c#wpfprismeventaggregator

Using generic PubSubEvents for Prism Eventaggregator WPF


I am trying to wrap access to Events from the EventAggregator of Prism for re-usability

Here's a sample code

protected void Subscription<T1,T2>(Action<T2> OnSubcribe) where T1:CachedEvent<T2>
{
    T1 @event  = _eventAggregator.GetEvent<T1>();
    event.Subcribe(OnSubcribe,true);
    //Some Codes other codes
}

I have placed a constraint on T1 , CachedEvent, which is a non-abstract derived class of PubSubEvent<TPayload>

But I am still getting an error

'T1' must be a non-abstract type with a public parameterless constructor in order to use it as parameter....

Assuming that this is not really valid in C#, are there any other alternatives?

UPDATE:

Here's what I did so far I have made@event a parameter

protected void Subscription<T1,T2>(T1 @event, Action<T2> OnSubcribe) where T1:CachedEvent<T2>
{
    @event.Subcribe(OnSubcribe,true);
    //Some Codes other codes
}

My Application works, but I'm still not free from the boiler point of creating the @event, calling the GetEvent manually, each time i call Subscription

example:

Subcription(eventAggregator.GetEvent<SomeEventBasedOnCachedEvent>(),AMethodDoneOnSubcribe);

Solution

  • What I've been missing all this time was the new() constraint for generic type T1.

    Apparently GetEvent<T> of Prism IEventAggregator requires that T must have a parameterless constructor.

    protected void Subscription<T1,T2>(Action<T2> OnSubcribe) where T1:CachedEvent<T2>,new()
    {
        T1 @event  = _eventAggregator.GetEvent<T1>();
        event.Subcribe(OnSubcribe,true);
        //Some Codes other codes
    }