0

I have setup an ASP.NET Core project, and configured the DbContext in Startup.cs like -

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DBContext>(options =>
        options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
}

I can access the DbContext object in controller classes with dependency injection. But I need a reference of the DbContext in the Program class (in Program.cs file).

I tried the following approach, but it indicates syntax error -

public class Program
{
    public static void Main(string[] args)
    {
        using (var db = new DBContext())    // getting syntax error here
        {
            db.Database.EnsureCreated();
        }
        CreateHostBuilder(args).Build().Run();
    }


    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>()
                    .UseUrls("http://localhost:4000");
            });
}

So, how to get access to the DbContext object in the Program class?

1
  • I need to find a way to get dbcontext in program.cs like we access the same in any other controller.. Commented Dec 22, 2020 at 11:56

1 Answer 1

4

Since you have registered and configured your database context using dependency injection, you cannot just create a context using new since you would be skipping the configuration that way.

Instead, you will need to retrieve the database context from the dependency injection service provider, which is available from the Host that is being built in your Program.

Since the database context has a scoped lifetime by default, you will need to create a scope first, retrieve the database context within that scope, and finally dispose the scope again when you are done.

This should look like this:

public static void Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var db = scope.ServiceProvider.GetRequiredService<DBContext>();
        db.Database.EnsureCreated();
    }

    host.Run();
}
Sign up to request clarification or add additional context in comments.

Comments

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.