question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Create Context without DI?

See original GitHub issue

If we want to create a fully self-configuring DbContext that doesn’t depend on DI, what’s the best way to do this?

In the previous beta I was able to access the Configuration instance directly and read the connectionstring info explicitly. However, in the current beta the configuration object appears that it needs a base path which has to come - from DI.

Here’s what I would roughly like to be able to do:

protected override void OnConfiguring(EntityOptionsBuilder optionsBuilder)
{
    base.OnConfiguring(optionsBuilder);

    if (optionsBuilder.IsConfigured)
        return;

    var builder = new ConfigurationBuilder();  // <--- this is the problem: needs basepath
    builder.AddJsonFile("config.json");
    var configuration = builder.Build();
    string conneMctionString = configuration.Get("Data:MusicStore:ConnectionString");

    optionsBuilder.UseSqlServer(connectionString);
}

My primary reason for this is that I’m not a fan of injected and scoped DbContext instances. In many applications I work on we often deal with multiple contexts in a single controller that aren’t used by all actions. There’s extra overhead for instantiating these instance, plus there are also few odds and ends where you need multiple contexts in order to keep multiple db operations isolated even when working against the same context type.

Anyway - in the past with EF 6 I typically build a self configuring context that runs off the parameterless constructor. Typically the code to set this up simply points at a connection strings entry and the rest is handled. I’d like to be able to do the same in EF7 as an alternative to feeding a configured instance through DI.

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:2
  • Comments:18 (10 by maintainers)

github_iconTop GitHub Comments

1reaction
ajcvickerscommented, Jul 27, 2015

@RickStrahl You can derive from DbContext and then just use ‘new’ to create an instance of your context, just like you could in older versions of EF. EF will still use DI to manage its own services, but it will be a separate container isolated from the rest of your application.

UseSqlServer just requires a connection string, which can be obtained in any way you want. In your sample code you are using ConfigurationBuilder. This is not an EF component and I don’t know if it can be used independently of DI or not. @divega might know more. But you certainly don’t need to use ConfigurationBuilder or any of its related classes in order to use EF.

0reactions
divegacommented, Aug 30, 2016

Just reading through discussion issues that has been sitting on my plate for a long time and trying to see if there is anything actionable.

It seems many of the EF Core related concerns mentioned in the thread been addressed by improvements, e.g.:

  • You can pass DbContextOptions in the constructor of DbContext which should make it easy to new up multiple DbContext instances in a request without changing where the DbContextOptions come (e.g. they can still com from DI)
  • If you pass DbContextOptions in the constructor you don’t need to have an OnConfiguring() method.
  • Plus we added optional lifetime parameters to AddDbContext() that allow making them transient by default, making it easier to create multiple instance of DbContext in a request but still use the application’s service provider.
  • DbContext now uses its own service provider by default,

The only outstanding issue seems to be the desire that the ASP.NET Core stack defined some static/global configuration mechanism which generic components can rely on always being present.

Although this is valid feedback (there is a tradeoff which leads to some loss of functionality of convenience) lack of such a static/global mechanism for configuration (or any other static/global mechanism for that matter) was actually a deliberate design decision by the ASP.NET team to favor designs that are more explicit about how configuration is passed and that are more testable.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Instantiate multiple DbContext manually without ...
I want to create an ASP.Net Core web service which will select rows from one SQL Server database and insert them into X...
Read more >
Create Context without DI? · Issue #2718 · dotnet/efcore
If we want to create a fully self-configuring DbContext that doesn't depend on DI, what's the best way to do this?
Read more >
How to create a DbContext from just a connection string?
NET Core web project, we'll be creating it by first specifying the DbContextOptions with DbContextOptionsBuilder and then just passing that on ...
Read more >
DbContext Lifetime, Configuration, and Initialization
Patterns for creating and managing DbContext instances with or without dependency injection.
Read more >
Best Practices in Using the DbContext in EF Core
A DbContext is often a lightweight object: creating and disposing of one does not require a database activity, and most applications may do...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found