Search code examples
c#mvvmdependency-injectiondotnet-httpclientmvvm-toolkit

AddHttpClient in Ioc.Default.ConfigureServices


I am refractoring an .NET C# application to the latest MS MVVM Toolkit. MS suggests the refit as a goto library to interact with REST API. However, I would like to use AddHttpClient following Ioc (Inversion of control) pattern. Below is the sample code I would like to refractor however it throws an error:

Ioc.Default.ConfigureServices(
    new ServiceCollection()
    //Services
    .AddSingleton<ISettingsService, SettingsService>()
    // Change below line to AddHttpClient
    .AddSingleton(RestService.For<IRedditService>("https://www.reddit.com/"))
    //ViewModels
    .AddTransient<PostWidgetViewModel>()
    //I would like to do below but it throws error
    .AddHttpClient<IRedditService>()
    .BuildServiceProvider());

So the question is how to register AddHttpClient in Ioc.Default.ConfigureServices?

Error

'IHttpClientBuilder' does not contain a definition for 'BuildServiceProvider' and the best extension method


Solution

  • First populate the collection

    var collection = new ServiceCollection();
    collection.AddSingleton<ISettingsService, SettingsService>();
    collection.AddSingleton(RestService.For<IRedditService>("https://www.reddit.com/"));
    collection.AddTransient<PostWidgetViewModel>();
    collection.AddHttpClient<IRedditService>();
    

    then you should call the BuildServiceProvider method on the ServiceCollection

    Ioc.Default.ConfigureServices(collection.BuildServiceProvider());