C# 检索服务并在NetCore中的任意类中使用它

C# 检索服务并在NetCore中的任意类中使用它,c#,.net-core,asp.net-core-3.0,C#,.net Core,Asp.net Core 3.0,有很多例子可以说明如何设置控制器以使用服务等,但是普通的旧类呢?让我们使用一些简单的配置服务 JSON 波科 公共类AppSettings { 公共字符串模式文件{get;set;} } 在startup.cs中 public void配置服务(IServiceCollection服务) { IConfigurationSection appSettingsSection=Configuration.GetSection(“AppSettings”); services.Configure(应

有很多例子可以说明如何设置控制器以使用服务等,但是普通的旧类呢?让我们使用一些简单的配置服务

JSON

波科

公共类AppSettings
{
公共字符串模式文件{get;set;}
}
在startup.cs中

public void配置服务(IServiceCollection服务)
{
IConfigurationSection appSettingsSection=Configuration.GetSection(“AppSettings”);
services.Configure(应用设置部分);
. . . . 
}
这是所有示例直接移动到控制器的点。但我们将有大量的代码在控制器之外。我需要的是使用
provider.GetService(typeof(T))
provider.GetRequiredService(typeof(T))
从静态类访问此服务

内部静态MyClass
{
内部静态空隙剂量测定法()
{
//获取我的服务
//使用它来检索一些值
//继续我的逻辑
}
}

谢谢

您应该将
AppSettings
作为调用者方法的参数传递

public class HomeController : Controller
{
   public HomeController(AppSettings settings)
   {
      this.Settings = settings;
   }

   private AppSettings Settings { get; }

   public IActionResult Index()
   {
      MyClass.DosomeThing(this.Settings);
   }
}

internal static MyClass
{
    internal static void DosomeThing(AppSettings settings)
    {
        // acquire my service
        // use it to retrieve some value
        // continue with my logic

    }
}

就像服务可以注入控制器一样,它们也可以被注入到其他类中

但是,静态类在默认情况下不适合依赖项注入

与其使用静态类,不如创建一个正则类,并通过构造函数注入显式地依赖于所需的服务

internal class MyClass : IMyService {
    readonly AppSettings settings;

    public MyClass(AppSettings settings) {
        this.settings = settings;
    }

    internal void DosomeThing() {
        // retrieve some value from settings
        // continue with my logic
    }
}
然后,您可以在服务容器中注册所需的POCO和实用程序

public void ConfigureServices(IServiceCollection services) {
    AppSettings appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
    services.AddSingleton(appSettings);
    services.AddSingleton<IMyService, MyClass>();
    //. . . . 
}
public void配置服务(IServiceCollection服务){
AppSettings AppSettings=Configuration.GetSection(“AppSettings”).Get();
services.AddSingleton(appSettings);
services.AddSingleton();
//. . . . 
}
在需要的地方注入您的服务,当解析为注入时,它将有权访问POCO

确实不需要到处传递IServiceProvider,因为这可以看作是一种代码气味


简化您的设计以遵循显式依赖原则应该会使您的代码更可靠,更易于遵循和维护。

这不是我想要的。然后,您必须(也应该)遵循以下原则。这是正确的类设计。我将用它来尝试。但我们这里有点不对劲。我的底线是,我希望在代码调用中的任何地方
MyClass.DoSomething
都是静态的,并且使用设置只初始化一次。然而,这仅仅是
Configuration.GetSection(“AppSettings”).Get()值得回答。这将打开解决我的问题的路径。感谢you@T.S.虽然get有效,但不应滥用它。它将直接用于
I配置
@T.S.上的ion startup。请查看此处的文档,了解如何使用它。我非常感谢您的回答。我将很快尝试全面实施。另外,在我的工作环境中,有一个更好的解决方案可以解决我们所做的事情——从框架迁移到核心。显然,微软现在有了针对.net内核的System.configuration nuget包。这为我解决了许多配置问题。但出于对所有这些的好奇,我将尝试并在可能的情况下实现这些与WebAPI/mvc项目直接相关的东西。然而,对于下面的所有层,我很高兴有前面提到的nuget包
public void ConfigureServices(IServiceCollection services) {
    AppSettings appSettings = Configuration.GetSection("AppSettings").Get<AppSettings>();
    services.AddSingleton(appSettings);
    services.AddSingleton<IMyService, MyClass>();
    //. . . . 
}