2

How to configure http client in App.xaml.cs or in any other file for my entire WinUI 3 application like we do in a dotnet core startup.cs file? I don't want to create multiple instances of http client.

App.xaml.cs


namespace MyNameSpace
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    public partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
        {
            m_window = new MainWindow();
            m_window.Activate();
        }

        private Window m_window;
    }
}
  • Just use [HttpClientFactory](https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests) – AndrewSilver Nov 07 '21 at 06:37

1 Answers1

2

Since there is only one App class instantiated in a desktop app, you could just create an instance of your HttpClient class in there and expose it using a property:

public partial class App : Application
{
    public App()
    {
        this.InitializeComponent();
    }

    public HttpClient HttpClient { get; } = new HttpClient();

    protected override void OnLaunched(Microsoft.UI.Xaml.LaunchActivatedEventArgs args)
    {
        m_window = new MainWindow();
        m_window.Activate();
    }

    private Window m_window;
}

Accessing it from other classes in your application is then easy using the static App.Current property:

var httpClient = (App.Current as App)?.HttpClient;
mm8
  • 163,881
  • 10
  • 57
  • 88