This is an add-in for Fody
![Build status](https://camo.githubusercontent.com/65d2f86b11b05f476d10c7062ea7a07d4a733fdd20649abcfdf1c602569e28ce/68747470733a2f2f63692e6170707665796f722e636f6d2f6170692f70726f6a656374732f7374617475732f733068707433726f6b6d7131626f39793f7376673d74727565)
Changes regular event handlers into weak event handlers by weaving a weak event adapter between source and subscriber. The subscriber is then no longer referenced by the event source, allowing it to be garbage collected. To understand the basic idea of a weak event adapter, see e.g. this Weak Events CodeProject article
Use this weaver if you have no control over the event source and can't change it into a weak event source.
Install the WeakEventHandler.Fody NuGet package and update the Fody NuGet package:
PM> Install-Package WeakEventHandler.Fody
PM> Update-Package Fody
The Update-Package Fody
is required since NuGet always defaults to the oldest, and most buggy, version of any dependency.
public class EventSubscriber
{
private readonly EventSource _source;
public EventSubscriber(EventSource source)
{
_source = source;
}
public void Subscribe()
{
_source.AnyEvent += Source_AnyEvent;
}
public void Unsubscribe()
{
_source.AnyEvent -= Source_AnyEvent;
}
[WeakEventHandler.MakeWeak]
private void Source_AnyEvent(object sender, EventArgs e)
{
// Do something
}
}
public class EventSubscriber
{
private readonly EventSource _source;
private readonly WeakEventAdapter<EventSource, EventSubscriber, EventArgs> EventSource_Source_AnyEvent_Adapter;
public EventSubscriber(EventSource source)
{
EventSource_Source_AnyEvent_Adapter = new WeakEventAdapter<EventSource, EventSubscriber, EventArgs>(
this,
Source_AnyEvent,
EventSource_Source_AnyEvent_Add,
EventSource_Source_AnyEvent_Remove);
_source = source;
}
public void Subscribe()
{
EventSource_Source_AnyEvent_Adapter.Subscribe(_source);
}
public void Unsubscribe()
{
EventSource_Source_AnyEvent_Adapter.Unsubscribe(_source);
}
private void Source_AnyEvent(object sender, EventArgs e)
{
// Do something
}
private static void EventSource_Source_AnyEvent_Add(EventSource source, EventHandler<EventArgs> handler)
{
source.EventA += handler;
}
private static void EventSource_Source_AnyEvent_Remove(EventSource source, EventHandler<EventArgs> handler)
{
source.EventA -= handler;
}
~EventSubscriber()
{
EventSource_Source_AnyEvent_Adapter.Release();
}
}
This code is only schematic to make it readable, the real implementation is slightly different!