How to define dependency injection in Winforms C#?
Interface ICategory:
public interface ICategory
{
void Save();
}
Class CategoryRepository:
public class CategoryRepository : ICategory
{
private readonly ApplicationDbContext _context;
public CategoryRepository(ApplicationDbContext contex)
{
_context = contex;
}
public void Save()
{
_context.SaveChanges();
}
}
Form1:
public partial class Form1 : Form
{
private readonly ICategury _ic;
public Form1(ICategury ic)
{
InitializeComponent();
_ic=ic
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm= new Form2();
frm.show();
}
}
Form2:
public partial class Form2 : Form
{
private readonly ICategury _ic;
public Form2(ICategury ic)
{
InitializeComponent();
_ic=ic
}
}
Problem?
Definition of dependency injection in Program.cs
Application.Run(new Form1());
Definition of dependency injection at the time of Form 2 call
Form2 frm= new Form2();
frm.show();
How to use Dependency Injection (DI) in Windows Forms (WinForms)
To use DI in a WinForms .NET 5 or 6 you can do the following steps:
Create a WinForms .NET Application
Install Microsoft.Extensions.Hosting package (which gives you a bunch of useful features like DI, Logging, Configurations, and etc.)
Add a new interface, IHelloService.cs:
public interface IHelloService
{
string SayHello();
}
Add a new implementation for your service HelloService.cs:
public class HelloService : IHelloService
{
public string SayHello()
{
return "Hello, world!";
}
}
Modify the Program.cs:
//using Microsoft.Extensions.DependencyInjection;
static class Program
{
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var host = CreateHostBuilder().Build();
ServiceProvider = host.Services;
Application.Run(ServiceProvider.GetRequiredService<Form1>());
}
public static IServiceProvider ServiceProvider { get; private set; }
static IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder()
.ConfigureServices((context, services)=>{
services.AddTransient<IHelloService, HelloService>();
services.AddTransient<Form1>();
});
}
}
Now you can inject IHelloService in Form1 and use it:
//using Microsoft.Extensions.DependencyInjection;
public partial class Form1 : Form
{
private readonly IHelloService helloService;
public Form1(IHelloService helloService)
{
InitializeComponent();
this.helloService = helloService;
MessageBox.Show(helloService.SayHello());
}
}
If you want to show Form2 using DI, you first need to register it services.AddTransient<Form2>();, then depending to the usage of Form2, you can use either of the following options:
If you only need a single instance of Form2 in the whole life time of Form1, then you can inject it as a dependency to the constructor of Form1 and store the instance and show it whenever you want.
But please pay attention: it will be initialized just once, when you open Form1 and it will not be initialized again. You also should not dispose it, because it's the only instance passed to Form1.
public Form1(IHelloService helloService, Form2 form2)
{
InitializeComponent();
form2.ShowDialog();
}
If you need multiple instances of Form2 or you need to initialize it multiple times, then you may get an instance of it like this:
using (var form2 = Program.ServiceProvider.GetRequiredService<Form2>())
form2.ShowDialog();
There's another approach than the one described by Reza in his answer. This answer of mine was originally published on my blog, however, since Stack Overflow is the primary source of information for most of us, the blog post linked in a comment below Reza's answer could easily be missed.
Here goes then. This solution is based on the Local Factory pattern.
We'll start with a form factory
public interface IFormFactory
{
Form1 CreateForm1();
Form2 CreateForm2();
}
public class FormFactory : IFormFactory
{
static IFormFactory _provider;
public static void SetProvider( IFormFactory provider )
{
_provider = provider;
}
public Form1 CreateForm1()
{
return _provider.CreateForm1();
}
public Form2 CreateForm2()
{
return _provider.CreateForm2();
}
}
From now on, this factory is the primary client's interface to creating forms. The client code is no longer supposed to just call
var form1 = new Form1();
No, it's forbidden. Instead, the client should always call
var form1 = new FormFactory().CreateForm1();
(and similarily for other forms).
Note that while the factory is implemented, it doesn't do anything on its own! Instead it delegates the creation to a somehow mysterious provider which has to be injected into the factory. The idea behind this is that the provider will be injected, once, in the Composition Root which is a place in the code, close to the startup, and very high in the application stack so that all dependencies can be resolved there. So, the form factory doesn't need to know what provider will be ultimately injected into it.
This approach has a significant advantage - depending on actual requirements, different providers can be injected, for example you could have a DI-based provider (we'll write it in a moment) for an actual application and a stub provider for unit tests.
Anyway, let's have a form with a dependency:
public partial class Form1 : Form
{
private IHelloWorldService _service;
public Form1(IHelloWorldService service)
{
InitializeComponent();
this._service = service;
}
}
This form depends on a service and the service will be provided by the constructor. If the Form1 needs to create another form, Form2, it does it it a way we already discussed:
var form2 = new FormFactory().CreateForm2();
Things become more complicated, though, when a form needs not only dependant services but also, just some free parameters (strings, ints etc.). Normally, you'd have a constructor
public Form2( string something, int somethingElse ) ...
but now you need something more like
public Form2( ISomeService service1, IAnotherService service2,
string something, int somethingElse ) ...
This is something we should really take a look into. Look once again, a real-life form possibly needs
some parameters that are resolved by the container
other parameters that should be provided by the form creator (not known by the container!).
How do we handle that?
To have a complete example, let's then modify the form factory
public interface IFormFactory
{
Form1 CreateForm1();
Form2 CreateForm2(string something);
}
public class FormFactory : IFormFactory
{
static IFormFactory _provider;
public static void SetProvider( IFormFactory provider )
{
_provider = provider;
}
public Form1 CreateForm1()
{
return _provider.CreateForm1();
}
public Form2 CreateForm2(string something)
{
return _provider.CreateForm2(something);
}
}
And let's see how forms are defined
public partial class Form1 : Form
{
private IHelloWorldService _service;
public Form1(IHelloWorldService service)
{
InitializeComponent();
this._service = service;
}
private void button1_Click( object sender, EventArgs e )
{
var form2 = new FormFactory().CreateForm2("foo");
form2.Show();
}
}
public partial class Form2 : Form
{
private IHelloWorldService _service;
private string _something;
public Form2(IHelloWorldService service, string something)
{
InitializeComponent();
this._service = service;
this._something = something;
this.Text = something;
}
}
Can you see a pattern here?
whenever a form (e.g. Form1) needs only dependand services, it's creation method in the FormFactory is empty (dependencies will be resolved by the container).
whenever a form (e.g. Form2) needs dependand services and other free parameters, it's creation method in the FormFactory contains a list of arguments corresponding to these free parameters (service dependencies will be resolved by the container)
Now finally to the Composition Root. Let's start with the service
public interface IHelloWorldService
{
string DoWork();
}
public class HelloWorldServiceImpl : IHelloWorldService
{
public string DoWork()
{
return "hello world service::do work";
}
}
Note that while the interface is supposed to be somewhere down in the stack (to be recognized by everyone), the implementation is free to be provided anywhere (forms don't need reference to the implementation!). Then, follows the starting code where the form factory is finally provided and the container is set up
internal static class Program
{
[STAThread]
static void Main()
{
var formFactory = CompositionRoot();
ApplicationConfiguration.Initialize();
Application.Run(formFactory.CreateForm1());
}
static IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => {
services.AddTransient<IHelloWorldService, HelloWorldServiceImpl>();
services.AddTransient<Form1>();
services.AddTransient<Func<string,Form2>>(
container =>
something =>
{
var helloWorldService =
container.GetRequiredService<IHelloWorldService>();
return new Form2(helloWorldService, something);
});
});
}
static IFormFactory CompositionRoot()
{
// host
var hostBuilder = CreateHostBuilder();
var host = hostBuilder.Build();
// container
var serviceProvider = host.Services;
// form factory
var formFactory = new FormFactoryImpl(serviceProvider);
FormFactory.SetProvider(formFactory);
return formFactory;
}
}
public class FormFactoryImpl : IFormFactory
{
private IServiceProvider _serviceProvider;
public FormFactoryImpl(IServiceProvider serviceProvider)
{
this._serviceProvider = serviceProvider;
}
public Form1 CreateForm1()
{
return _serviceProvider.GetRequiredService<Form1>();
}
public Form2 CreateForm2(string something)
{
var _form2Factory = _serviceProvider.GetRequiredService<Func<string, Form2>>();
return _form2Factory( something );
}
}
First note how the container is created with Host.CreateDefaultBuilder, an easy task. Then note how services are registered and how forms are registered among other services.
This is straightforward for forms that don't have any dependencies, it's just
services.AddTransient<Form1>();
However, if a form needs both services and free parameters, it's registered as ... form creation function, a Func of any free parameters that returns actual form. Take a look at this
services.AddTransient<Func<string,Form2>>(
container =>
something =>
{
var helloWorldService = container.GetRequiredService<IHelloWorldService>();
return new Form2(helloWorldService, something);
});
That's clever. We register a form factory function using one of registration mechanisms that itself uses a factory function (yes, a factory that uses another factory, a Factception. Feel free to take a short break if you feel lost here). Our registered function, the Func<string, Form2> has a single parameter, the something (that corresponds to the free parameter of the form constructor) but its other dependencies are resolved ... by the container (which is what we wanted).
This is why the actual form factory needs to pay attention of what it resolves. A simple form is resolved as follows
return _serviceProvider.GetRequiredService<Form1>();
where the other is resolved in two steps. We first resolve the factory function and then use the creation's method parameter to feed it to the function:
var _form2Factory = _serviceProvider.GetRequiredService<Func<string, Form2>>();
return _form2Factory( something );
And, that's it. Whenever a form is created, is either
new FormFactory().CreateForm1();
for "simple" forms (with service dependencies only) or just
new FormFactory().CreateForm2("foo");
for forms that need both service dependncies and other free parameters.
Just wanted to add this here too as an alternative pattern for the IFormFactory. This is how I usually approach it.
The benefit is you don't need to keep changing your IFormFactory interface foreach form that you add and each set of parameters.
Load all forms when application starts and pass arguments to the show method or some other base method you can define on your forms.
internal static class Program
{
public static IServiceProvider ServiceProvider { get; private set; }
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
ServiceProvider = CreateHostBuilder().Build().Services;
Application.Run(ServiceProvider.GetService<Form1>());
}
static IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder()
.ConfigureServices((context, services) => {
services.AddSingleton<IFormFactory,FormFactory>();
services.AddSingleton<IProductRepository, ProductRepository>();
//Add all forms
var forms = typeof(Program).Assembly
.GetTypes()
.Where(t => t.BaseType == typeof(Form))
.ToList();
forms.ForEach(form =>
{
services.AddTransient(form);
});
});
}
}
Form Factory
public interface IFormFactory
{
T? Create<T>() where T : Form;
}
public class FormFactory : IFormFactory
{
private readonly IServiceScope _scope;
public FormFactory(IServiceScopeFactory scopeFactory)
{
_scope = scopeFactory.CreateScope();
}
public T? Create<T>() where T : Form
{
return _scope.ServiceProvider.GetService<T>();
}
}
Form 1
public partial class Form1 : Form
{
private readonly IFormFactory _formFactory;
public Form1(IFormFactory formFactory)
{
InitializeComponent();
_formFactory = formFactory;
}
private void button_Click(object sender, EventArgs e)
{
var form2 = _formFactory.Create<Form2>();
form2?.Show(99);
}
}
Form 2
public partial class Form2 : Form
{
private readonly IProductRepository _productRepository;
public Form2(IProductRepository productRepository)
{
InitializeComponent();
_productRepository = productRepository;
}
public void Show(int recordId)
{
var product = _productRepository.GetProduct(recordId);
//Bind your controls etc
this.Show();
}
}
I have a developing a c# windows form application and I have a method that exists inside the main form class.
Imagine methodA as part of the main form class.
public void methodA() {
A.someMethod();
B.someMethod();
// some more code
if (someCondition) {
// execute some code
}
// initialize timer and set event handler for timer
// run new thread
}
class A {
someMethod() {...}
}
class B {
someMethod() {...}
}
How would I run tests to test the branch logic of this methodA (isCondition)? since it involves initializing timer and running threads. Can i only verify the logic while doing system test ? I dont think it is possible to mock the timer and threading function.
Thank you !
Of course you can mock the timer. This is by creating a new interface, say, ITimerWrapper and implement it by using the concrete Timer class. Basically a wrapper of the Timer class. Then use that instead of the concrete Timer class you have.
Something in the tune of:
public partial class Form1 : Form
{
private readonly ITimerWrapper _timerWrapper;
public Form1(ITimerWrapper timerWrapper)
{
InitializeComponent();
this._timerWrapper = timerWrapper; // of course this is done via dependency injection
this._timerWrapper.Interval = 1000;
}
private void Form1_Load(object sender, EventArgs e)
{
// now you can mock this interface
this._timerWrapper.AddTickHandler(this.Tick_Event);
this._timerWrapper.Start();
}
private void Tick_Event(object sender, EventArgs e)
{
Console.WriteLine("tick tock");
}
}
public interface ITimerWrapper
{
void AddTickHandler(EventHandler eventHandler);
void Start();
void Stop();
int Interval { get; set; }
}
public class TimerWrapper : ITimerWrapper
{
private readonly Timer _timer;
public TimerWrapper()
{
this._timer = new Timer();
}
public int Interval
{
get
{
return this._timer.Interval;
}
set
{
this._timer.Interval = value;
}
}
public void AddTickHandler(EventHandler eventHandler)
{
this._timer.Tick += eventHandler;
}
public void Start()
{
this._timer.Start();
}
public void Stop()
{
this._timer.Stop();
}
}
Then for the spinning of a new thread, that's also testable by doing the same thing.
Bottomline is to have an interface to separate concerns and mock the interface on your unit test.
I just wanted to ask if the following code is a valid method to access the GUI from another class, or if it is bad practice. What I want to do is to write log messages into a RichTextBox in Form1.
If it's bad practice, would it be better to pass a reference of my Form1 to the other class to be able to access the RichTextBox.
I have the following code to access the GUI in my Form1 from another class:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Logger.Init(this.rtbLog);
MyOtherClass myOtherClass = new MyOtherClass();
myOtherClass.DoSomething();
}
}
public class MyOtherClass
{
public void DoSomething()
{
Logger.AppendText("text...");
Logger.AppendText("text...");
Logger.AppendText("text...");
}
}
public static class Logger
{
private static RichTextBox _rtb;
public static void Init(RichTextBox rtb)
{
_rtb = rtb;
}
public static void AppendText(String text)
{
_rtb.AppendText(text);
_rtb.AppendText(Environment.NewLine);
}
}
With Events (thanks to Ondrej):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Logger.EntryWritten += Logger_EntryWritten;
MyOtherClass myOtherClass = new MyOtherClass();
myOtherClass.DoSomething();
}
void Logger_EntryWritten(object sender, LogEntryEventArgs args)
{
rtbLog.AppendText(args.Message);
rtbLog.AppendText(Environment.NewLine);
}
}
public class MyOtherClass
{
public void DoSomething()
{
Logger.AppendText("text...");
Logger.AppendText("text...");
Logger.AppendText("text...");
}
}
public static class Logger
{
public static event EventHandler<LogEntryEventArgs> EntryWritten;
public static void AppendText(string text)
{
var tmp = EntryWritten;
if (tmp != null)
tmp(null, new LogEntryEventArgs(text));
}
}
public class LogEntryEventArgs : EventArgs
{
private readonly String message;
public LogEntryEventArgs(String pMessage)
{
message = pMessage;
}
public String Message
{
get { return message; }
}
}
It's probably fine for a small throw-away project, but otherwise a logger should not know anything about used platform. Then it would be good to use events for example. Raise an event whenever there's a new log entry written and consumers interested in logged entries will subscribe to a delegate.
Also be careful with threads. If you log a message from a different thread than UI you will end up with an exception because you would access a GUI control from a different thread which is forbidden.
EDIT:
Something along these lines. LogEntryEventArgs is a type you have to create and you can give it properties like Message, TimeWritten, Severity, etc.
public static class Logger
{
public static event EventHandler<LogEntryEventArgs> EntryWritten;
public static void AppendText(string text)
{
var tmp = EntryWritten;
if (tmp != null)
tmp(null, new LogEntryEventArgs(text));
}
}
consumer:
Logger.EntryWritten += Logger_OnEntryWritten;
void Logger_OnEntryWritten(object sender, LogEntryEventArgs args)
{
_rtb.AppendText(args.Message);
_rtb.AppendText(Environment.NewLine);
}
Also, don't forget to invoke on a form/dispatch the body of Logger_OnEntryWritten in order to avoid cross-thread access exception (in case you are considering using threads).
I have a Program class which has:
private static ClientBase objClientBase = new ClientBase(new List<RecordType> { RecordType.none }, ModuleType.Monitor);
static void Main(string[] args)
{
objClientBase.Connect(); //IRRELEVANT
objQueueMon = new Main(); //<-INSIDE THIS IS WHERE I WANT TO ACCESS objClientBase
objClientBase.MainModuleThreadManualResetEvent.WaitOne(); //IRRELEVANT
}
This Progam creates a Main class instance as you see:
objQueueMon = new Main();
Notice that they are separated in different files, but the Main class instance is created inside the Program class.
Inside my Program class I want to access that objClientBase.
Do I have to create a constructor method and pass it or make a public access to it?
So what I want to achieve is, inside the Main class, do a objClientBase.FUNCTION
You can do exactly what you just said:
public class Main {
private ClientBase _caller;
public Main (ClientBase caller) {
_caller = caller;
}
}
Or, you can set it later
public class Main {
private ClientBase _caller;
public Main () {
}
// only your assembly sets it
internal SetClientBase(ClientBase cb) {
_caller = cb;
}
// but anyone gets it
// Now you can let some client execute "Function"
public ClientBase Caller {
{return _caller;}
}
}
Just an example
Change the constructor of your Main class to accept a ClientBase object, like this:
public class Main
{
private ClientBase _clientBase;
public Main(ClientBase clientBase)
{
_clientBase = clientBase;
}
public void SomeMethod()
{
// Use ClientBase.FUNCTION here
_clientBase.FUNCTION();
}
}
Application c:\pinkPanther.exe is running and it is application i wrote in c#.
Some other application starts c:\pinkPanther.exe purpleAligator greenGazelle OrangeOrangutan and i would like not to start new instance of c:\pinkPanther.exe with these arguments, but to currently running c:\pinkPanther.exe register it and react to it somehow.
How to do it?
EDIT!!!: i'm very sorry about pinkPanther.exe and ruzovyJeliman.exe that caused the confusion - i translated question from my native language and missed it :(
This is assuming your application is a WinForms app, as that will make it easier to keep it open. This is a very simple example, but it will show you the basics:
Add a reference to Microsoft.VisualBasic.
Create an Application class inheriting from WindowsFormsApplicationBase. This base class contains built-in mechanisms for creating a single-instance application and responding to repeated calls on the commandline with new arguments:
using Microsoft.VisualBasic.ApplicationServices;
//omitted namespace
public class MyApp : WindowsFormsApplicationBase {
private static MyApp _myapp;
public static void Run( Form startupform ) {
_myapp = new MyApp( startupform );
_myapp.StartupNextInstance += new Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventHandler( _myapp_StartupNextInstance );
_myapp.Run( Environment.GetCommandLineArgs() );
}
static void _myapp_StartupNextInstance( object sender, Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs e ) {
//e.CommandLine contains the new commandline arguments
// this is where you do what you want with the new commandline arguments
// if you want it the window to come to the front:
e.BringToForeground = true;
}
private MyApp( Form mainform ) {
this.IsSingleInstance = true;
this.MainForm = mainform;
}
}
All you have to change in Main() is call Run() on your new class rather than Application.Run():
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
MyApp.Run( new MyMainForm() );
}
}
WindowsFormsApplicationBase has some other capabilities you can explore, as well.
To communicate with the other instance of the application, you need some sort of inter-process communication. Apparently, WCF is the recommended form of IPC in .Net. You can do that with code like this (using WPF, but WinForms would be similar):
[ServiceContract]
public interface ISingletonProgram
{
[OperationContract]
void CallWithArguments(string[] args);
}
class SingletonProgram : ISingletonProgram
{
public void CallWithArguments(string[] args)
{
// handle the arguments somehow
}
}
public partial class App : Application
{
private readonly Mutex m_mutex;
private ServiceHost m_serviceHost;
private static string EndpointUri =
"net.pipe://localhost/RuzovyJeliman/singletonProgram";
public App()
{
// find out whether other instance exists
bool createdNew;
m_mutex = new Mutex(true, "RůžovýJeliman", out createdNew);
if (!createdNew)
{
// other instance exists, call it and exit
CallService();
Shutdown();
return;
}
// other instance does not exist
// start the service to accept calls and show UI
StartService();
// show the main window here
// you can also process this instance's command line arguments
}
private static void CallService()
{
var factory = new ChannelFactory<ISingletonProgram>(
new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), EndpointUri);
var singletonProgram = factory.CreateChannel();
singletonProgram.CallWithArguments(Environment.GetCommandLineArgs());
}
private void StartService()
{
m_serviceHost = new ServiceHost(typeof(SingletonProgram));
m_serviceHost.AddServiceEndpoint(
typeof(ISingletonProgram),
new NetNamedPipeBinding(NetNamedPipeSecurityMode.None),
EndpointUri);
m_serviceHost.Open();
}
protected override void OnExit(ExitEventArgs e)
{
if (m_serviceHost != null)
m_serviceHost.Close();
m_mutex.Dispose();
base.OnExit(e);
}
}