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
Now, in 2022, with increasing competition and the adoption of newer more modern technologies the popularity and usage of WinForms are at an all-time low.
The latest version of Windows Forms is for . NET 6 using Visual Studio 2022 version 17.0. The . NET Framework 4 implementation that's supported by Visual Studio 2022, Visual Studio 2019, and Visual Studio 2017.
You can use GDI+ to render graphical images on Windows Forms and controls. Although you cannot use GDI+ directly on Web Forms, you can display graphical images through the Image Web Server control.
Win Form has been used to develop many applications. Because of its high age (born in 2003), WinForm was officially declared dead by Microsoft in 2014.
You're trying to get the System.Type
instance that corresponds to that class.
That's what the typeof()
keyword does:
GetService(typeof(MainForm))
Note that you'll also need to cast the result to Form
.
I've added a helper function to my code to make this more readable:
public static T? GetService<T>() where T : class
{
return (T?)ServiceProvider.GetService(typeof(T));
}
//was:
// thing = (iThing)Program.ServiceProvider.GetService(typeof(iThing));
//now:
thing = Program.GetService<iThing>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With