gpt4 book ai didi

asp.net-core - .NET Core 2、DI、配置文件

转载 作者:行者123 更新时间:2023-12-03 18:32:27 25 4
gpt4 key购买 nike

我正在学习 .NET Core 2,但我不喜欢 DI 的管理方式……在网上我读到了类似以下步骤的内容:

  • 创建像 IService
  • 这样的接口(interface)
  • 为 IService
  • 创建一个实现
  • 将其添加到 .NET Core 容器的范围内,以解决依赖关系的 Startup.Configuration 方法。
  • 最后我可以在我的自定义 Controller 的构造函数中使用它。

  • 在 .NET 经典中,我使用专用的 XML 配置文件来管理依赖项:我可以使用配置文件(JSON 或 XML 相同)来做我在 Startup.Configuration 方法中必须做的事情吗?

    ...否则有人可以向我解释为什么将服务配置到 Startup.Configuration 是更好的方法?

    非常感谢...

    最佳答案

    首先,要回答您的问题“我可以使用配置文件吗”,答案肯定是"is"。为什么不应该稍后回答你,但现在,这是一个穷人的版本,你可以通过添加到你的 appsettings.json 来做到这一点。文件。请注意,此代码不是最佳代码,而是旨在向您展示如何实现此解决方案。

    让我们从一些保存数据的类开始:

    public class ServicesConfiguration
    {
    public IEnumerable<ServiceItem> Singleton { get; set; }
    public IEnumerable<ServiceItem> Transient { get; set; }
    }

    public class ServiceItem
    {
    public string Service { get; set; }
    public string Implementation { get; set; }
    }

    现在向您的 JSON 文件添加一个部分,您甚至可能希望将此文件保留在主配置之外,但这是我将留给您的实现细节:

    {
    //snip main config....

    "Services" : {
    "Singleton": [
    {
    "Service": "YourNamespace.IFoo1, YourNamespace",
    "Implementation": "YourNamespace.Foo1, YourNamespace"
    },
    {
    "Service": "YourNamespace.IFoo2, YourNamespace",
    "Implementation": "YourNamespace.Foo2, YourNamespace"
    }
    ],
    "Transient": [
    {
    "Service": "YourNamespace.IBar1, YourNamespace",
    "Implementation": "YourNamespace.Bar1, YourNamespace"
    }
    ]
    }
    }

    现在有一个扩展方法来配置它:

    public static IServiceCollection AddFromConfigurationFile(this IServiceCollection services, 
    IConfigurationSection configuration)
    {
    var servicesConfiguration = configuration.Get<ServicesConfiguration>();

    foreach(var service in servicesConfiguration.Singleton)
    {
    services.AddSingleton(Type.GetType(service.Service), Type.GetType(service.Implementation));
    }

    foreach(var service in servicesConfiguration.Transient)
    {
    services.AddTransient(Type.GetType(service.Service), Type.GetType(service.Implementation));
    }

    //Other scopes here...

    return services;
    }

    并调用 ConifigureServices像这样:

    services.AddFromConfigurationFile(Configuration.GetSection("Services"));

    那么,又好又简单,对吧?为什么不应该这样做?我脑海中浮现出一些想法:
  • 为什么要改变几乎所有 DI 实现的工作方式?如果它没有坏,为什么要修复它?仅仅因为你习惯了一种特定的方法,并不意味着它是一个好主意。
  • 类型安全:您会丢失在配置文件中指定的类型的编译时检查。
  • 安全性:在配置文件中包含它可以让某人将实现更改为他们自己选择的类。

  • 我敢肯定还有更多,但是......这是你的应用程序!

    关于asp.net-core - .NET Core 2、DI、配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52258845/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com