How to add db context not in ConfigureServices method ASP.NET Core

asp.net-core entity-framework-core

Question

Is there any posibility to add a db context in external class/method "on fly?" When I run the application, there is no any connection string, so I need to generate a db after typing some information(server, dbname, ect)

1
2
9/12/2017 2:32:10 PM

Accepted Answer

One way is to use the factory pattern, i.e. creating a service that will be used to create new instances of your context.

Here is an example, it is not a final solution and you will need to adapt it to your needs but it should give you an idea of the technique:

public interface IDbContextFactory
{
    DbContext CreateDbContext(string connectionString);
}

public class DbContextFactory : IDbContextFactory
{
    public DbContext CreateDbContext(string connectionString)
    {
        return new DbContext(connectionString);
    }
}

Then in asp.net core, you can register the context factory and inject it in your controller:

 services.AddSingleton<IDbContextFactory, DbContextFactory>();

 public class SomeController
 {
      private IDbContextFactory contextFactory;

      public SomeController(IDbContextFactory contextFactory)
      {
          this.contextFactory = contextFactory;
      }

      public IActionResult Index()
      {     
         using(var db = contextFactory.CreateDbContext("Your connection string"))    {
              //Get some data
         }
         return View();
     }
 }

Instead of creating a DbContext you could combine the factory pattern with the unit of work and / or repository patterns to better separate concerns and to make sure you always dispose the context, etc...

7
5/14/2019 11:51:53 AM

Popular Answer

Use new YourContext(new DbContextOptionsBuilder<YourContext>().Use...().Options)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow