How to Register IHttpClientFactory in MVVM Ligtht MainViewmodel

1k views Asked by At

I am using MVVM Light to write a WPF App, my initial idea is to use Static Httpclient for abstracting data from multiple devices, there is a issue regarding the DNS with Static Httpclient. So, If I am going to use IHttpClientFactory, How should i go about setting up?

What I read is My MainViewModel Constructor will need to do this:

 public class MainViewModel : ViewModelBase
{
    /// <summary>
    /// Initializes a new instance of the MainViewModel class.
    /// </summary>
    /// 

    private readonly IHttpClientFactory httpClientFactory;
   
    public MainViewModel(IHttpClientFactory httpClientFactory)
    {
        this.httpClientFactory = httpClientFactory;
        var client = httpClientFactory.CreateClient();
    }

}

I have 2 problems here:

a) I am unable to register MainViewModel at ViewLocator

 public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);

        if (ViewModelBase.IsInDesignModeStatic)
        {
            // Create design time view services and models
           // SimpleIoc.Default.Register<IDataService, DesignDataService>();
        }
        else
        {
        ///    // Create run time view services and models
            //SimpleIoc.Default.Register<IDataService, DataService>();
       }

         SimpleIoc.Default.Register<IHttpClientFactory, MainViewModel>();  
        
    }

     public MainViewModel Main
    {
        get
        {
            return ServiceLocator.Current.GetInstance< MainViewModel>(); --> Error
            "ServiceLocator.ActivationException: 'Type not found in cache: "
        }
    }

b) Is below require at start up and where should i use this method ?

 private void ConfigureServices(IServiceCollection services)
    {
        // ...

        services.AddHttpClient();

        services.AddTransient(typeof(MainWindow));  ---> ? valid for MVVM?
    }

Or anyone has use IHttpClientFactory in WPF with MVVM Light?

Thanks

Simon

1

There are 1 answers

0
mm8 On BEST ANSWER

You could use the HostBuilder in Microsoft.Extensions.Hosting to create a DI container in the ViewModelLocator:

public class ViewModelLocator
{
    private readonly IServiceProvider _serviceProvider;

    public ViewModelLocator()
    {
        _serviceProvider = new HostBuilder()
            .ConfigureServices(ConfigureServices)
            .Build()
            .Services;
    }

    public MainViewModel Main =>
        _serviceProvider.GetService<MainViewModel>();

    private void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();
        services.AddSingleton<MainViewModel>();
    }
}