3

I am writing a .NET 6 console app and have this unfinished code below. I don't know how to get the connection string from configuration such that I can pass it to the options.UseSqlServer method.

I prefer using the top level statements template.

Also, should I call hostBuilder.Build().Run(); at the end of this code? Or just hostBuilder.Build()? Just wondering what the difference is.

var hostBuilder = Host.CreateDefaultBuilder(args)
    .ConfigureAppConfiguration((context, builder) =>
    {
        builder.SetBasePath(Directory.GetCurrentDirectory());
    })
    .ConfigureServices((context, services) =>
    {
        services.AddDbContext<CompanyContext>(options => options.UseSqlServer("<connection string from config"));
    });

2 Answers 2

5

An ASP.NET Core web app is actually a console app that starts an HTTP server. The DI, logging, configuration infrastructure is the same in both cases. The same methods you see in ASP.NET Core tutorials can be used in console applications through the Generic Host Builder.

The Configuration is available through the HostBuilderContext parameter of the ConfigureServices delegate :

.ConfigureServices((context, services) =>
{
    var cns=context.Configuration.GetConnectionString("MyConnection");
    services.AddDbContext<CompanyContext>(options.UseSqlServer(cns));
});

The WebApplicationBuilder class introduced in .NET (Core) 6.0 still uses the Microsoft.Extensions.Hosting middleware under the hood, but exposes Services, Configuration, Logging etc as properties instead of methods like ConfigureServices to enable top-level and minimal API programs.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. would you also please provide an answer for "Also, should I call hostBuilder.Build().Run(); at the end of this code? Or just hostBuilder.Build()? Just wondering what the difference is."?
That's explained in the .NET Generic Host docs. With Build() you create the host instance with all its services and configuration. With Run you start any hosted services and the lifecycle hooks that will terminate the services when the application terminates
2

I am working on a .NET 6.0 console app with EFCore and I have exactly the same issue. Thanks to your answers I could manage to make the db-scaffolding to work again...

IHost host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((config) =>
{
    config.AddJsonFile("appsettings.json");
    config.AddEnvironmentVariables();
    config.Build();
})

.ConfigureServices((context, services) =>
{
    var cns = context.Configuration.GetConnectionString("DiBerieBotDB");
    services.AddDbContext<DiBerieBotEntities>(options => options.UseSqlServer(cns))
    //.AddHostedService<DiBerieBotMain>();
    ;
})
.Build();

List<User> theUsers = new List<User>();
using (var context = new DiBerieBotEntities())
{
    theUsers = (from usr in context.Users.Include("Channels")
                select usr).ToList();
}

host.Run();

but on the first Linq query that occurs, the program crashs :

Crash on running Linq query

Also my console app "DiBerieBot.Console" and the DAL "DiBerieBot.DAL" (where the EFCore DbContext class is) are on separate projects : Projects

Any idea ?

1 Comment

Ok, I finally managed to get over this one. It's a bit dumb... but I simply added the dbContext class with DI in my HostedService constructor, and it worked as it always did in ASP .NET Core... From here I have been able to simply expose one unique dbContext instance for all the app's lifetime, and so never encounter the "NamedConnection" error !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.