Reputation: 11796
I am working on a way for my ASP.NET C# application to allow plugins without recompiling the host application when new plugins are installed.
Here's my plugin loader class (based on tutorials found online.)
public class PluginLoader
{
public static IList<IPlugin> Load(string folder)
{
IList<IPlugin> plugins = new List<IPlugin>();
// Get files in folder
string[] files = Directory.GetFiles(folder, "*.plug.dll");
foreach(string file in files)
{
Assembly assembly = Assembly.LoadFile(file);
var types = assembly.GetExportedTypes();
foreach (Type type in types)
{
if (type.GetInterfaces().Contains(typeof(IPlugin)))
{
object instance = Activator.CreateInstance(type);
plugins.Add(instance as IPlugin);
}
}
}
return plugins;
}
}
The concept is to create a IPlugin interface in the host application that new plugins can use. The loader then searches through the available DLLs and finds the classes that are of the IPlugin type. then those get instantiated and my host application can use them how it sees fit.
For example it could do this:
protected void Page_Load(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
string folder = Server.MapPath("~/bin/");
path.Text = folder;
var plugins = PluginLoader.Load(folder);
if (plugins.Count == 0)
sb.Append("No plugins found");
else
{
sb.Append("<ul>");
foreach (var plug in plugins)
{
sb.AppendFormat("<li>Default: {0}</li>", plug.Label);
plug.SetLabel("Overwrote default label.");
sb.AppendFormat("<li>New: {0}</li>", plug.Label);
}
sb.Append("</ul>");
}
message.Text = sb.ToString();
}
Is this structure what IoC or DI is? The plugin is referencing the host, rather than the other way around. This seems to be consistent with the Inversion Of Control concept. Is there a fundamental difference between this code and IoC/DI?
Upvotes: 2
Views: 839
Reputation: 2713
Agree with Richard's answer. I think what you have ends up being a rudimentary service locator. A DI container would provide the actual auto-instantiation of types based on other types in the container.
Upvotes: 1
Reputation: 84724
This looks like a plugin architecture that utilises Inversion of Control, but not using Dependency Injection. It appears to be similar to the way MEF works.
Upvotes: 2