I searched for an event subscription using a weak event pattern. With the .NET 4.5 platform, we have the sleek WeakEventManager class. Slightly subscribing to an event is as easy as
WeakEventManager<EventSource, SomeEventEventArgs>.AddHandler(source, "SomeEvent", source_SomeEvent);
However, I am not a big fan of string input. I am trying to find a way to use a string name for a subscription. the only way I found to get the name of the event uses the lambda expression in the class that defines the event. In my scenario, I have a class that defines an event, so I can change it as I like. I tried to find a clean way to subscribe and unsubscribe to my event, and here's what I didn't like.
public event EventHandler<EventArgs> LoggingOn; public event EventHandler<EventArgs> LoggingOn_Weak { add { var eventName = this.GetEventName(() => this.LoggingOn); WeakEventManager<CurrentUser, EventArgs>.AddHandler(this, eventName, value); } remove { var eventName = this.GetEventName(() => this.LoggingOn); WeakEventManager<CurrentUser, EventArgs>.RemoveHandler(this, eventName, value); } }
Using custom event assemblers I managed to avoid clumsy (in my opinion) methods, such as LoggingOn_Subscribe (EventHandler) or adding name properties for each event. Unfortunately, this is not so intuitive that people who sign up for the event do it classically, but have no idea, except for the "_Weak" part of the name, which indicates that it is poorly subscribed.
As for my questions ..
1) I've never used weak events or custom event accessors before. The above code seems to work, however I would just like to make sure there is nothing technically with it. Is there something I am doing here to shoot the leg?
2) In terms of design, is this a terrible idea? Are there any serious design issues that I should consider? Is there a better alternative? Should I just suck it and subscribe from my subscriber using a string-typed event name?
Thoughts?