asp.net-core - IOptions<T> 的简化方法

标签 asp.net-core dependency-injection asp.net-core-2.1 .net-4.7.1

我试图在使用内置 DI 机制的同时获得与 ASP.NET Core 2.1 应用程序一致的 .NET Framework 类库。现在,我创建了一个配置类并将适当的部分添加到 appsettings.json:

services.Configure<MyConfig>(Configuration.GetSection("MyConfiguration"));
services.AddScoped<MyService>();

在类库中:
public class MyService 
{
    private readonly MyConfig _config;

    public MyService(IOptions<MyConfig> config)
    {
        _config = config.Value;
    }
}

但是,为了构建这个类库,我必须添加 Microsoft.Extensions.Options NuGet 包。问题是这个包携带了大量的依赖项,这些依赖项看起来相当多,只是为了一个接口(interface)而添加。

enter image description here

所以,最终的问题是,“我可以采取另一种方法来配置位于 .NET Framework 类库中的 DI 服务,它的依赖关系不重吗?

最佳答案

查看 Filip Wojcieszyn 撰写的这篇文章。

https://www.strathweb.com/2016/09/strongly-typed-configuration-in-asp-net-core-without-ioptionst/

您添加扩展方法:

public static class ServiceCollectionExtensions
{
    public static TConfig ConfigurePOCO<TConfig>(this IServiceCollection services, IConfiguration configuration) where TConfig : class, new()
    {
        if (services == null) throw new ArgumentNullException(nameof(services));
        if (configuration == null) throw new ArgumentNullException(nameof(configuration));

        var config = new TConfig();
        configuration.Bind(config);
        services.AddSingleton(config);
        return config;
    }
}

在配置中应用它:
public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.ConfigurePOCO<MySettings>(Configuration.GetSection("MySettings"));
}

然后使用它:
public class DummyService
{
    public DummyService(MySettings settings)
    {
        //do stuff
    }
}

关于asp.net-core - IOptions<T> 的简化方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51894213/

相关文章:

c# - 如何在 asp.net core 中将 json 请求正文验证为有效的 json

asp.net-core - 使用 appsettings.json 覆盖特定接收器的 serilog minimumlevel

azure - family_name 和 Give_name 未包含在 AzureAD token 声明中

asp.net-core - Asp.net Core 中的用户主机地址

.net - IIS 在不关闭 IIS 网站的情况下发布 ASP.NET Core 应用程序

javascript - Angular DI 注入(inject)的 super 代理的正确类型是什么?

c# - 如何在 ASP.net Core 2 中创建动态 API

c# - 单独库中 Controller 的动态路由前缀

java - 在springboot中获取存储库对象为空

angular - 为 Angular 4 中的所有组件注入(inject)服务作为单例