asp.net-core – 简化的IOptions方法
发布时间:2020-05-24 10:58:38 所属栏目:asp.Net 来源:互联网
导读:我正在尝试使用内置DI机制获得符合ASP.NET Core 2.1应用程序的.NET Framework类库.现在,我创建了一个配置类,并为appsettings.json添加了适当的部分: services.ConfigureMyConfig(Configuration.GetSection(MyConfiguration));services.AddScopedMyService
|
我正在尝试使用内置DI机制获得符合ASP.NET Core 2.1应用程序的.NET Framework类库.现在,我创建了一个配置类,并为appsettings.json添加了适当的部分: services.Configure<MyConfig>(Configuration.GetSection("MyConfiguration"));
services.AddScoped<MyService>();
在类lib中: public class MyService
{
private readonly MyConfig _config;
public MyService(IOptions<MyConfig> config)
{
_config = config.Value;
}
}
但是,为了构建这个classlib,我必须添加Microsoft.Extensions.Options NuGet包.问题是,程序包带有很多依赖项,看起来相当过分,只是为了一个接口而添加. 因此,最终的问题是,“我可以采用另一种方法来配置位于.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-mvc – 什么是ASP.NET MVC的验证选项
- asp.net – OutputCache和RenderAction缓存整个页面
- asp.net – HttpPostedFileBase.SaveAs方法问题
- asp.net-mvc – Asp.Net MVC使用来自JQuery UI选项卡的ajax
- asp.net – IIS 7.5无法打开处理程序映射?
- asp.net-mvc – 捕获文件名作为参数的MVC路由
- asp.net核心 – Microsoft Asp.Net 5 RC1
- asp.net – LinkButton CommandName和CommandArgument
- ASP.NET 2.0 JQuery AJAX登录
- 无法从按钮onclick事件ASP.NET 4调用Javascript函数
