DIの知識は非常に限られています。 解決策の中で、Microsoft Extension Dependency Injectionが使用されているすべてのソリューションで、WinFormプロジェクトを開発しています。C#のWinFormsでのMicrosoft拡張依存関係注入の使用
IがのMainFormのコンストラクタに一部依存性を渡す必要がある:メインメソッドで
public partial class MainForm : Form
{
public MainForm(ISomeThing someThing)
{
}
}
、のMainFormのインスタンスは、メソッドを実行するために渡される。
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
私はDIを使用しようとしました
private static IServiceProvider ServiceProvider { get; set; }
を入力してMainformのインスタンスをインスタンス化します。次のようにオブジェクトをINGの:その後、
static void ConfigureServices()
{
var services = new ServiceCollection();
services.AddTransient<ISomeThing, SomeThing>();
ServiceProvider = services.BuildServiceProvider();
}
、次のようにMain()
にConfigureServices()
を呼び出す:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ConfigureServices();
Application.Run(ServiceProvider.GetService(MainForm));
}
しかし、私はコンパイルエラーが出ます:「のMainFormは有効ではありませんタイプです指定されたコンテキスト「
に私はSimpleInjectorかUnity を使用して、同様のアプローチを使用して、次のリンクを見つけましたが、私は、nを行いますこの種のDIでこれを使う方法を知っていますか?または私は他のDIを使用する必要がありますか?
おかげ
ありがとうございます。私はあなたの提案ごとにこのように使用しましたvar form =(MainForm)ServiceProvider.GetService(typeof(MainForm)); Application.Run(form);ただし、フォームオブジェクトはnullです。 –
@AminMerati:あなたはあなたのServiceProviderにそれを追加する必要があります。 – SLaks
助けてくれてありがとう、それは今働いた! –