简体   繁体   中英

Can't create service on .net core 3 with boolean

I have this class :

public class ApiService
    {
        public bool Success { get; set; }
        public object Data { get; set; }
        public ApiService(bool success, object data)
        {
            this.Success = success;
            this.Data = data;
        }
    }

I try to add it to the service in the startup.cs with this line :

 services.AddSingleton<ApiService>();

But I have this exception :

Unhandled exception. System.AggregateException: 
Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: ApiService Lifetime: Singleton ImplementationType: 
ApiService': 
Unable to resolve service for type 'System.Boolean' while attempting to activate ApiService'.)

Thank's in advance if someone can resolve this problem.

Best regards.

尝试:

services.AddSingleton<ApiService>(new ApiService(true,null));

This can only work if the arguments in the constructor are both interfaces and registered in the DI pipeline. If you want to use concrete types like this you have to supply the values when you register

services.AddSingleton<ApiService>(new ApiService(false,data));

It doesn't know what values you want put into this constructor. The other option would be to provide a default constructor that has no arguments.

But really, you don't need to register this class with Dependency Injection because this class has no dependencies to inject in the first place. If you really only want one instance of this throughout your application make it static. Singletons are an anti-pattern.

This is happening because your class constructor demands 2 parameter. What the error says is that the dependency injector engine tried to create an instance of your class but failed because you're not passing those 2 parameters bool success, object data You can register your dependency using services.AddSingleton<ApiService>(new ApiService(true,null));

But I strongly discourage you to create a service like this. Take a look here Dependency Injection .

Create an interface for your service and remove those constructor parameters. So you'll be able to register your service like this: services.AddSingleton<IApiService, ApiService>(); with this you'll be able to inject your IApiService anywhere on your application just passing it on their constructor.

public class MyOtherClass 
{
      private readonly IApiService  _myService;
      public MyOtherClass(IApiService myService) 
      {
            _myService = myService;
      }
}

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