2

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
  • show some code in a minimal reproducible example that better explains what you are trying to say. Right now it is unclear what you're asking. Read How to Ask Commented Sep 12, 2017 at 14:41

2 Answers 2

7

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...

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

1 Comment

This answer got me to solve my own solution working with .net core 2.1 / signalr core and needed to setup a dbContextFactory as normal dbContext gets disposed inside a hub. The only minor update needed here (for later versions) is now we call IDesignTimeDbContextFactory, instead of IDbContextFactory. More information can be found here: https://learn.microsoft.com/en-us/ef/core/miscellaneous/cli/dbcontext-creation
0

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

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.