Home > Back-end >  System.ArgumentNullException: 'Value cannot be null. Parameter name: provider'
System.ArgumentNullException: 'Value cannot be null. Parameter name: provider'

Time:05-16

I'm trying to consume a web api that adds a user in a database, so I created this startup class:

    public static class Startup
    {
        private static IServiceProvider serviceProvider;
        public static void ConfigureServices()
        {
            var services = new ServiceCollection();
            //add services
            services.AddHttpClient<IUserServices, ApiUserServices>(c => 
            {
                c.BaseAddress = new Uri("http://10.0.2.2:9129/api/");
                c.DefaultRequestHeaders.Add("Accept", "application/json");
            });

            //add viewmodels
            services.AddTransient<SignUpPageViewModel>();

            serviceProvider = services.BuildServiceProvider();
        }
  

        public static T Resolve<T>() => serviceProvider.GetService<T>();

    }

But I got this exception: System.ArgumentNullException: 'Value cannot be null. Parameter name: provider'

CodePudding user response:

Firstly you should initialize service provider before register SignUpViewModel because the Resolve method use serviceProvider inside itself . Probably you are using Resolve method in your code . Need to check your code

CodePudding user response:

In XamWebApiClient / App.xaml.cs, see the constructor:

        public App()
        {
            InitializeComponent();

            Startup.ConfigureServices();   <-- Do you have this line?
          
            MainPage = new AppShell();
        }

The line Startup.ConfigureServices(); is called before setting MainPage.

That sets serviceProvider, so should fix the null exception.

EXPLANATION: "Resolve" gets called to find the implementation of any services needed by HTTPClient.

In your case, code elsewhere probably refers to IUserServices?

ConfigureServices must be called before that code tries to use IUserServices.


IMPORTANT: If you have OTHER services that are used, but not declared in ConfigureServices, then you'll still get a null exception on that Resolve line. In that case, find on VS Call Stack the line that shows what "service" is asked for.

ConfigureServices will need another services.AddHttpClient<ISomeService, ... for that service. (replace ISomeService with whatever Interface defines that service.)

  • Related