I am trying to introduce DI (with Autofac) into an existing Windows Forms application.
This application has a basic plug-in architecture where each plugin displays its own form. On startup, the application scans registered assemblies for types that implement IPlugin
, and then activates these using Activator.CreateInstance
:
public interface IPlugin
{
Form MainForm { get; }
}
I cannot change this given framework. This means, each plugin class is instantiated through non-DI means, and it seems to me that I will therefore have to bootstrap a separate DI container for each plugin.
My question is, is creating a separate ContainerBuilder
and container per plugin OK and still reasonably efficient? (There will be approx. 10 different plugins.) Or should there only be one DI container for the whole application?
I've provided some sample code of my current solution below.
using Autofac;
using System.Windows.Forms;
public class Plugin : IPlugin // instantiated by Activator
{
public Form MainForm { get; private set; }
public Plugin() // parameter-less constructor required by plugin framework
{
var builder = new ContainerBuilder();
builder.RegisterModule(new Configuration());
var container = builder.Build();
MainForm = container.Resolve<MainForm>();
// ^ preferred to new MainForm(...) because this way, I can take
// advantage of having dependencies auto-wired by the container.
}
}
internal class Configuration : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MainForm>().SingleInstance();
// ... more plugin-specific registrations go here...
}
}
internal class MainForm : Form { /* ... */ }
I'm also not sure whether creating a container in the plugin constructor and then simply forgetting about it, but leaving it to do auto-wiring in the background, is OK?