![](/img/trans.png)
[英].NET Core 2.1 DbContext ObjectDisposedException Dependency Injection
[英]Net Core 3.0 dependency injection interface that the dbcontext derived from
有沒有辦法依賴注入接口一個DbContext
class 是從Startup
class 派生的?
下面是DbContent
class
public partial class SRSDbContext : IdentityDbContext<SRSIdentityUser>, ISRSDbContext
{
public SRSDbContext()
{
//...
在Startup
class 我嘗試使用代碼
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ISRSDbContext>(opts =>
opts.UseSqlServer(Configuration.GetConnectionString("sqlConnection")));
但是上面這行代碼沒有識別到ISRSDbContext
接口。
我喜歡使用AppsSetting.json
文件中定義的連接字符串注冊ISRSDbContext
以進行依賴注入
使用采用接口及其派生實現的AddDbContext
重載
//...
services.AddDbContext<ISRSDbContext, SRSDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("sqlConnection")));
//...
如果接口在單獨的庫中注冊,還要確保它被調用代碼的庫引用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.