Ric*_*ham 4 c# constructor entity-framework-core asp.net-core
在新的 MVC Core 中,获取控制器上下文的标准方法似乎是这样做
public class BaseController : Controller
{
public readonly ReportDBContext _db;
public BaseController(ReportDBContext db)
{
_db = db;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以使用
public class HomeController : BaseController
{
public HomeController(ReportDBContext db) : base(db) { }
}
Run Code Online (Sandbox Code Playgroud)
为了使这在所有其他控制器中变得更容易一些。通常在 Asp.net MVC 中我可以通过使用随时获取上下文new ReportDBContext()
现在是否有类似的方法,或者我是否必须在 asp.core MVC 中的所有控制器中拥有上下文?
感谢@mm8的回答,如果您决定使用依赖注入,那么您可以按照下面提到的步骤操作。
假设您已经ReportDBContext 这样定义了您的:
public class ReportDBContext : DbContext
{
public DbSet<Sample> Samples { get; set; }
//...
public ReportDBContext(DbContextOptions<ReportDBContext> options) : base(options)
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
所以你需要startup.cs这样配置:
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
//...What needed
services.AddDbContext<ReportDBContext>(options => options.UseSqlServer("Connection string to your DB"));
//...What needed
}
//...
}
Run Code Online (Sandbox Code Playgroud)
因此,您可以ReportDBContext像这样轻松地将您的类注入到您的类中(例如将其注入到您的控制器之一):
[Route("api/[controller]")]
public class ValuesController : Controller
{
private readonly ReportDBContext _dbContext;
public ValuesController(ReportDBContext dbContext )
{
_dbContext = dbContext;
}
//...
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地将其注入ReportDBContext到您的控制器中BaseController,而不是将其注入到项目中的每个控制器中。
更新1
如果您不想将其注入ReportDBContext到每个构造函数中,那么您可以BaseController使用 HttpContext.RequestServices 进行如下设计:
public class BaseController : Controller
{
protected ReportDBContext DbContext => (ReportDBContext)HttpContext.RequestServices.GetService(typeof(ReportDBContext));
//...
}
[Route("api/[controller]")]
public class ValuesController : BaseController
{
//...
[HttpGet]
public List<Sample> Get() => DbContext.Samples.ToList();
}
Run Code Online (Sandbox Code Playgroud)
在这里阅读更多内容:
您还需要至少安装这两个 NuGet 包:
| 归档时间: |
|
| 查看次数: |
13645 次 |
| 最近记录: |