Problem z rejestracja klasy jako singleton

0

Cześć zrobiłem sobie taką klasę:

public class ApiClient : IApiClient
    {
        public string Address { get; set; }

        public ApiClient(string address)
        {
            this.Address = address;
        }
        public void SendRequest()
        {
            throw new NotImplementedException();
        }
    }

Chciałbym ją teraz zarejestrować jako singleton, w startup.cs dodaje:

services.AddSingleton<IApiClient>(new ApiClient(address));

Ale w momencie wstrzykiwania do konstruktora innej klasy dostaje:
Unable to resolve service for type 'IApiClient' while attempting to activate...

Co robie nie tak?

0

A czy próbujesz do singletona wstrzyknąć transient albo scoped?

http://morgwai.pl/articles/aspdi.html

0

Nie żebym się znał, ale nie powinno być?

services.AddSingleton<IApiClient, ApiClient>(new ApiClient(address));
0

Po części sugerowałem się tym: https://stackoverflow.com/a/34834352
@Dregorio to co Ty podałeś się nie skompiluje.
Mam w IApplicationBuilder zrobione globalne przechwytywanie errorow i tam mi wyłapuje wyjątek.
StackTrace:

   at Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
   at lambda_method9(Closure , IServiceProvider , Object[] )
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
1

Chryste Panie, zrobiłem to sobie jako extension method dla IServiceCollection, a koniec końców zapomniałem tą metodę wywołać... Wszystko działa.

1 użytkowników online, w tym zalogowanych: 0, gości: 1