如何从Main内部获取IConfiguration?

编程入门 行业动态 更新时间:2024-10-28 10:24:22
本文介绍了如何从Main内部获取IConfiguration?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下内容仅供参考.

我有一个 secrets.json ,其内容如下:

I have a secrets.json with the following contents:

{ "Message": "I still know what you did last summer." }

我需要使用以下播种器为数据库播种.

And I need to seed the database with the following seeder.

public static class SeedData { public static void Initialize(IServiceProvider isp, IConfiguration c) { using (var context = isp.GetRequiredService<MyContext>()) { if (context.Members.Any()) return; context.Members.AddRange ( new Member { Message= c["Message"] } ); context.SaveChanges(); } } }

播种器在 Main 内部调用如下.

The seeder is invoked inside Main as follows.

public static void Main(string[] args) { IWebHost iwh = BuildWebHost(args); using (IServiceScope iss = iwh.Services.CreateScope()) { IServiceProvider isp = iss.ServiceProvider; try { // IConfiguration c = ?????? SeedData.Initialize(isp, c); } catch (Exception ex) { ILogger<Program> logger = isp.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred seeding the DB."); } } iwh.Run(); }

问题

如何从 Main 获取 IConfiguration c ?

推荐答案

您将执行与 MyContext 服务相同的操作:

You would do just as you do for your MyContext service:

var configuration = isp.GetRequiredService<IConfiguration>();

最好将两个依赖项都传递给 SeedData.Initialize 而不是依赖项和IoC容器:

It'd be better if you passed both dependencies to SeedData.Initialize instead of a dependency and the IoC container:

public static void Initialize(MyContext context, IConfiguration config) { ... } IServiceProvider isp = iss.ServiceProvider; try { var configuration = isp.GetRequiredService<IConfiguration>(); var context = isp.GetRequiredService<MyContext>(); SeedData.Initialize(context, configuration); }

这样,您至少要避免使用 Initialize 方法中的Service Locator反模式.

With this, you at least avoid the Service Locator anti-pattern in the Initialize method.

更多推荐

如何从Main内部获取IConfiguration?

本文发布于:2023-11-14 21:42:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588570.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Main   IConfiguration

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!