如何在ConfigureServices方法ASP.NET Core中添加数据库上下文 [英] How to add db context not in ConfigureServices method ASP.NET Core
问题描述
是否可以在外部类/方法中即时添加数据库上下文?当我运行应用程序时,没有任何连接字符串,因此我需要在输入一些信息(服务器,数据库名称等)后生成数据库。
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)
推荐答案
一种方法是使用工厂模式,即创建将用于创建上下文的新实例的服务。
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);
}
}
然后在asp.net核心中,您可以注册上下文工厂并将其注入到您的控制器中:
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();
}
}
除了创建DbContext之外,您还可以结合使用工厂模式使用工作单元和/或存储库模式可以更好地分离关注点,并确保始终处理上下文等。
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...
这篇关于如何在ConfigureServices方法ASP.NET Core中添加数据库上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!