My knowledge in DI is very limited. I am developing a WinForm project in a solution which every else where in the solution, Microsoft Extension Dependency Injection have been used.
I need to pass some dependency into constructor of MainForm:
public partial class MainForm : Form
{
public MainForm(ISomeThing someThing)
{
}
}
In the Main method, an instance of MainForm is passed to Run method:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
I tried to use DI to instantiate an instance for Mainform by having a service provider:
private static IServiceProvider ServiceProvider { get; set; }
and then assigning to it an object as follows:
static void ConfigureServices()
{
var services = new ServiceCollection();
services.AddTransient<ISomeThing, SomeThing>();
ServiceProvider = services.BuildServiceProvider();
}
And then call ConfigureServices() in Main() as follows:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ConfigureServices();
Application.Run(ServiceProvider.GetService(MainForm));
}
However, I get a compilation error: "MainForm is a type, which is not valid in the given context"
I found the following links which uses similar approach using SimpleInjector or Unity but I do not know how to use this with this kind of DI? or I have to use other DI?
Thanks