如何从Main内部获取IConfiguration

如何从Main内部获取IConfiguration

本文介绍了如何从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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 07:54