gpt4 book ai didi

asp.net-core - IOptions 的简化方法

转载 作者:行者123 更新时间:2023-12-04 08:02:11 27 4
gpt4 key购买 nike

我试图在使用内置 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/

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