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

笑着哭i 提交于 2019-12-13 16:32:40

问题


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:


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




回答2:


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



来源:https://stackoverflow.com/questions/46179023/how-to-add-db-context-not-in-configureservices-method-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!