-1

We want to fire Events, with event names saved in SQL Server

In the SQL Server you'll find ApplicationExitRequestEvent When we click the menu button, we'll get the string from the MenuItem

Type t = Type.GetType(SelectedMenu.View + "," + "AssemblyName");
var obj = Activator.CreateInstance(t);

if (t != null)
{
//Working firing Event with className
EventAggregator.GetEvent<ApplicationExitRequestEvent>().Publish(null);

//Generic?
EventAggregator.GetEvent<???>().Publish(null);
}

Ist it possible to do? Working with PRISM and MVVM - WPF - .NET 4.0

David Müller
  • 97
  • 2
  • 8
  • See [this question](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) on how to call a generic method using reflection. It's probably not best practice to do so though if performance is an issue. – Adi Lester Mar 08 '12 at 10:01
  • thx. `MethodInfo method = EventAggregator.GetType().GetMethod("GetEvent"); MethodInfo generic = method.MakeGenericMethod(typeof(ApplicationExitRequestEvent)); generic.Invoke(this, null);` Doesn't work. any idea? – David Müller Mar 08 '12 at 14:53
  • Object isn't equal to target object?! – David Müller Mar 08 '12 at 15:06

2 Answers2

0

if you look at the EventAggregator class, you'll see it's nothing more than a container Dictionary<Type, EventBase> and the GetEvent method. That's it, all the actual work is done in EventBase. In order to achieve what you want, you could modify the class (or make a copy and modify that), and add a method GetEvent( string typeString ) in which you convert the typeString to an actual Type (same way as in your code sample) and use that to fetch the event from the dictionary.

stijn
  • 34,664
  • 13
  • 111
  • 163
  • get the source at http://compositewpf.codeplex.com/SourceControl/list/changesets and start typing :] – stijn Mar 08 '12 at 15:14
0

Got it, working fine now! Pimped the Prism Library, to get the event by Type :-)

    /// <summary>
    /// Gets the single instance of the event managed by this EventAggregator. 
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
    public CompositePresentationEvent<object> GetEvent(Type type)
    {
        EventBase existingEvent = null;
        events.TryGetValue(type, out existingEvent);

        if(existingEvent != null)
            return (CompositePresentationEvent<object>)existingEvent;

        return null;
    }

Thank you guys!

David Müller
  • 97
  • 2
  • 8