简体   繁体   中英

System.ArgumentNullException: 'Value cannot be null. Parameter name: provider'

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'

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

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM