1
votes

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);
1
I dabbled with a similar issue and concluded that it was not worth the headaches; go with a parent class.Kilazur
I've seen your query just now. going for parent class with generics won't do for my app because of how it was built. furthermore, eventaggregators.Getevent will only be accessed through generic inputs of types.M Ktsis D

1 Answers

0
votes

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
}