dependency injection in Windows forms and EF core

Vojislav Ćeklić 26 Reputation points
2021-02-17T22:08:04.857+00:00

Hi there,

I am trying to find some info on how to properly do dependency injection on ,NET Windows Forms with EF Core in the mix. Could someone point me to a right drection? (Sample project would be great.) Thanks a lot.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,835 questions
{count} vote

Accepted answer
  1. Daniel Zhang-MSFT 9,616 Reputation points
    2021-02-19T07:59:32.763+00:00

    Hi Vojislavekli-4660,
    Here is an example that injecting the IBusinessLayer and ILogger object through Forms object, and you can refer to.
    And Generic HostBuilder was introduced in .NET Core 2.1.
    1.Create a Windows FormsApp(.NET Core).
    2.Add ConfigureServices() method:
    Please add below ConfigureServices() method. This method can be used for registering all the required services within Service collection.

    private static void ConfigureServices(ServiceCollection services)  
    {  
        services.AddLogging(configure => configure.AddConsole())  
                .AddScoped<IBusinessLayer, CBusinessLayer>()  
                .AddScoped<IBusinessLayer, CBusinessLayer>()  
                .AddSingleton<IDataAccessLayer,CDataAccessLayer>();  
    }  
    

    3.Add Form1 which is currently my master Form and has the UI logic. Please register Form1 to above as services.

      services.AddScoped<Form1>()  
    

    4.Adding DI Container:
    Please update the Main() method as below.
    We shall be injecting ILogger and IBusinessLayer object is as below.

    [STAThread]  
    static void Main()  
    {  
        Application.SetHighDpiMode(HighDpiMode.SystemAware);  
        Application.EnableVisualStyles();  
        Application.SetCompatibleTextRenderingDefault(false);  
    
        var services = new ServiceCollection();  
    
        ConfigureServices(services);  
    
        using (ServiceProvider serviceProvider = services.BuildServiceProvider())  
        {  
            var form1 = serviceProvider.GetRequiredService<Form1>();  
            Application.Run(form1);  
        }  
    }  
    

    Here we are assuming Form1 is the master form that holds other forms together.
    5.Add IBusinessObject and ILogger using DI to Forms App

    public partial class Form1 : Form  
        {  
            private readonly ILogger _logger;  
    
            private readonly IBusinessLayer _business;  
            public Form1(ILogger<Form1> logger, IBusinessLayer business)  
            {  
                _logger = logger;  
                _business = business;  
                InitializeComponent();  
            }  
    
            private void button1_Click(object sender, EventArgs e)  
            {  
                try  
                {  
                    _logger.LogInformation("Form1 {BusinessLayerEvent} at {dateTime}", "Started", DateTime.UtcNow);  
    
                    // Perform Business Logic here   
                    _business.PerformBusiness();  
    
                    MessageBox.Show("Hello .NET Core 3.0 . This is First Forms app in .NET Core");  
    
                    _logger.LogInformation("Form1 {BusinessLayerEvent} at {dateTime}", "Ended", DateTime.UtcNow);  
    
                }  
                catch (Exception ex)  
                {  
                    //Log technical exception   
                    _logger.LogError(ex.Message);  
                    //Return exception repsponse here  
                    throw;  
    
                }  
    
            }  
        }  
    

    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,616 Reputation points
    2021-02-18T03:09:11.16+00:00

    Hi Vojislavekli-4660,
    One approach of DI is using Service collection and ServiceProvider for Windows forms app.
    You can also use Generic HostBuilder to create DI Container and inject the required dependency within the Windows Forms app.
    Here are some related threads and hope these are helpful to you.
    Using Microsoft Extension Dependency Injection on WinForms in C#
    Dependency Injection in WindowsForm Application C#
    Dependency Injection in WinForms using Ninject and Entity Framework
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments