【问题标题】:Can't create service on .net core 3 with boolean无法使用布尔值在 .net core 3 上创建服务
【发布时间】:2020-01-10 19:28:11
【问题描述】:

我有这门课:

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;
        }
    }

我尝试使用这一行将其添加到 startup.cs 中的服务:

 services.AddSingleton<ApiService>();

但我有这个例外:

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

如果有人可以解决此问题,请提前感谢。

最好的问候。

【问题讨论】:

    标签: c# asp.net-core service boolean asp.net-core-3.0


    【解决方案1】:

    尝试:

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

    【讨论】:

      【解决方案2】:

      这只有在构造函数中的参数都是接口并且在 DI 管道中注册时才有效。如果你想使用这样的具体类型,你必须在注册时提供值

      services.AddSingleton&lt;ApiService&gt;(new ApiService(false,data));

      它不知道你想把什么值放入这个构造函数中。另一种选择是提供一个没有参数的默认构造函数。

      但实际上,您不需要使用 Dependency Injection 注册这个类,因为这个类首先没有要注入的依赖项。如果您真的只想要整个应用程序中的一个实例,请将其设为静态。单例是一种反模式。

      【讨论】:

        【解决方案3】:

        发生这种情况是因为您的类构造函数需要 2 个参数。错误说的是依赖注入引擎试图创建你的类的一个实例但失败了,因为你没有传递这两个参数bool success, object data 您可以使用 services.AddSingleton&lt;ApiService&gt;(new ApiService(true,null)); 注册您的依赖项

        但我强烈不鼓励您创建这样的服务。看看这里Dependency Injection

        为您的服务创建一个接口并删除那些构造函数参数。所以你可以像这样注册你的服务:services.AddSingleton&lt;IApiService, ApiService&gt;(); 这样你就可以在你的应用程序的任何地方注入你的 IApiService ,只需将它传递给他们的构造函数。

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

        【讨论】:

        • 非常感谢,我会这么做的!
        • 酷!如果此答案对您有用,请选择正确@LucasGassiot
        猜你喜欢
        • 1970-01-01
        • 2018-05-23
        • 2019-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多