简体   繁体   English

如何使用控制台应用程序中的通用主机从 appsettings 中获取连接字符串?

[英]How do I get the connection string out of appsettings using a generic host in console application?

Environment:环境:

<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.7" />

SQL Server 2016 SQL Server 2016
.NET Core 3.1 .NET 核心 3.1

I have a working snippet of a console application below that gets connection string out of appsettings but it feels like I have too much code and I should be able to combine some of this but not sure how.我有一个console application的工作片段,它从appsettings中获取连接字符串,但感觉我有太多代码,我应该能够结合其中的一些,但不确定如何结合。

class Program
{
    static void Main(string[] args)
    {
        CreateHostBuilder(args);
    }

    public static void CreateHostBuilder(string[] args)
    {
        IConfiguration config = new ConfigurationBuilder()
            .AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"), true, true)
            .Build();

        var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) =>
            {
                services.AddTransient<App>();
                services.AddDbContext<SchoolContext>(options =>
                options.UseSqlServer(config["ConnectionStrings:MyDatabase"]));
            })
            .Build();

        ActivatorUtilities.CreateInstance<Startup>(host.Services);
    }
}

Update更新
Based on @andy's answer below...基于@andy在下面的回答......

class Program
{
    static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        host.RunAsync().GetAwaiter();

        ActivatorUtilities.CreateInstance<Startup>(host.Services);
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args).ConfigureServices((context, services) =>
        {
            var config = context.Configuration; // grab from here
            services.AddTransient<App>();
            services.AddDbContext<SchoolContext>(options =>
            options.UseSqlServer(config["ConnectionStrings:MyDatabase"]));
        });
}

You already created a default builder which includes your appsettings.json file.您已经创建了一个默认构建器,其中包含您的appsettings.json文件。 You can get at it by grabbing it from the context in ConfigureServices您可以通过从ConfigureServices的上下文中获取它来获取它

class Program
{
    static Task Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        return host.RunAsync();
    }

    /* or you can use a synchronous main:
    static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();
        host.Run();
    }
    */

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args).ConfigureServices((context, services) =>
        {
            var config = context.Configuration; // grab from here
            services.AddTransient<App>();
            services.AddDbContext<SchoolContext>(options =>
                options.UseSqlServer(config["ConnectionStrings:MyDatabase"]));
        });
}

I also refactored your code a bit to show you a typical create/build/run scenario with a generic host.我还对您的代码进行了一些重构,以向您展示使用通用主机的典型创建/构建/运行场景。

ETA预计到达时间

Here is some shameless self-promotion: I came up with a way to move this logic to the good ol' IWebHostBuilder / Startup.cs pattern that we all know and love.这是一些无耻的自我宣传:我想出了一种方法来将这种逻辑转移到我们都知道和喜爱的优秀的IWebHostBuilder / Startup.cs模式中。 If interested, check this out .如果有兴趣,看看这个

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 appsettings.json 中设置连接字符串? - How do I set up a connection string into appsettings.json? 如何在控制台应用程序中设置默认连接字符串? - How do I set a default connection string in a console application? 如何在使用 .NET Core 的控制台应用程序中从 appsettings.json 获取值? - How to get values from appsettings.json in a console application using .NET Core? 如何从已部署的应用程序获取连接字符串? - How do I get a connection string from a deployed application? 如何在 a.Net 6 控制台应用程序中读取 appsettings.json? - How can I read the appsettings.json in a .Net 6 console application? 如何在我的控制台应用程序中使用 appSettings 中的值创建循环 - How to create a loop using values from appSettings in my console application 如何使用C#从SQL Server连接字符串或IIS应用程序名称获取应用程序名称? - How do I get the Application Name from either SQL Server connection string or the IIS application name using C#? 使用 .NET 通用主机的控制台应用程序过早退出 - Console application using .NET Generic Host exits too early 如何在控制台应用程序中添加 appsettings.json - How to add a appsettings.json in a console application 现在可以在从 Windows 任务调度程序运行 .net 核心控制台应用程序时读取 appsettings.json 文件中存在的连接字符串 - Now able to read the Connection String present in appsettings.json file when running the .net core Console application from windows task scheduler
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM