既存の Windows フォーム アプリケーションに( Autofacを使用して) DI を導入しようとしています。
このアプリケーションには、各プラグインが独自のフォームを表示する基本的なプラグイン アーキテクチャがあります。起動時に、アプリケーションは を実装する型の登録済みアセンブリをスキャンしIPlugin
、 を使用してこれらをアクティブ化しActivator.CreateInstance
ます。
public interface IPlugin
{
Form MainForm { get; }
}
このフレームワークを変更することはできません。つまり、各プラグイン クラスは DI 以外の方法でインスタンス化されるため、プラグインごとに個別の DI コンテナーをブートストラップする必要があるように思えます。
私の質問はContainerBuilder
、プラグインごとに別のコンテナーを作成しても問題なく、それでもかなり効率的ですか? (約 10 の異なるプラグインがあります。) または、アプリケーション全体に対して 1 つの DI コンテナーのみが必要ですか?
以下に、現在のソリューションのサンプル コードをいくつか示します。
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 { /* ... */ }
また、プラグイン コンストラクターでコンテナーを作成し、単にそれを忘れているかどうかもわかりませんが、バックグラウンドで自動配線を行うためにそのままにしておいても問題ありませんか?