aspnetcore icon indicating copy to clipboard operation
aspnetcore copied to clipboard

Dependency Injection question

Open dlr1 opened this issue 8 years ago • 3 comments

I have the following code for service

    {
        private readonly HttpClient _httpClient;
        public MyService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        public async Task<List<DriverStanding>> GetDrivers()
        {            
            var data = await _httpClient.GetJsonAsync<Root>("driverStandings.json");
            return data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
        }
    }

registered like below

  var serviceProvider = new BrowserServiceProvider(services =>
            {
               services.AddSingleton<IMyService, MyService>();
            });

and use the service in a code behind file like below and it doesn't work

        public DriversBase(IMyService service)
        {
            _service = service;
        }

I get error "There is no argument given that corresponds to the required formal parameter 'service' of 'DriversBase.DriversBase(IMyService)'"

while the following works

[Inject]
        private IMyService _service { get; set; }
        public DriversBase()
        {            
            Console.WriteLine("ctor....");
        }

dlr1 avatar Apr 13 '18 14:04 dlr1

Yes, the DI system does property injection, not constructor injection. There's a proposal at aspnet/AspNetCore#5497 to support constructor injection too.

SteveSandersonMS avatar Apr 13 '18 14:04 SteveSandersonMS

@SteveSandersonMS do we have a way to get the service by manual call? just likes

services.GetService<T>()

hungdluit avatar May 13 '18 12:05 hungdluit

@hungdluit yes, see https://github.com/aspnet/Blazor/issues/819#issuecomment-388417917

Suchiman avatar May 13 '18 13:05 Suchiman