I am trying to create a plugin system for my application by defining a common interface and then loading the assemblies dynamically in the current App-domain through reflection. Here is the code for main application:
var asm = Assembly.Load(an);
var types = asm.GetTypes();
foreach (var type in types)
{
if (type.GetInterface(typeof(IModule).ToString()) != null)
{
IModule module = null;
try
{
module = asm.CreateInstance(type.ToString(), true) as IModule;
}
catch (Exception)
{
}
if (module != null)
{
_modules.Add(module);//These objects implement plugin interface
}
}
}
Problem is that even though I am caching the IModule objects of the plugin at class level, it seems to be garbage collected. Here is the plugin code to demonstrate the problem:
internal class SamplePlugin : IModule
{
public void Initialize() // IModule implementation
{
_timer = new System.Timers.Timer(1000);
_timer.Enabled = true;
_timer.Elapsed += TimerElapsed;
}
//This method never gets called
void TimerElapsed(object sender, ElapsedEventArgs e)
{
}
}
The initialize method gets called successfully when I call the initialize method on cached IModule objects. But the TimerElapsed method never gets called, suggesting that the object has been garbage collected by CLR.