asp.net-core - AddDbContext 在 1 个请求中创建 2 个实例
问题描述
我有一个带有 EF 2 核心的 ASP.NET 核心 2.1 应用程序我正在使用内置 DI 我像这样注册我的类:在 Startup.cs 中,在 ConfigureServices
var connectionString = this.configuration.GetConnectionString("MYConnection");
services.AddDbContext<IMyContext, MyContext>(
options => options.UseSqlServer(connectionString));
services.AddScoped<IMy1Dao, My1Dao>();
services.AddScoped<IMy2Dao, My2Dao>();
services.AddScoped<IMyService, MyService>();
我注入这样的类:
public class MyController : Controller, IMyController{
private readonly IMyService myService;
public MyController(IMyService myService)
{
this.myService = myService;
}
public async Task<List<MyBatchUIDTO>> GetMyBatches([FromBody]List<short> ids)
{
return await myService.GetMyBatches(ids);
}
}
public class MyService : IMyService{
private readonly IMy1Dao my1Dao;
private readonly IMy2Dao my2Dao;
public MyService(IMy1Dao my1Dao, IMy2Dao my2Dao)
{
this.my1Dao = my1Dao;
this.my2Dao = my2Dao;
}
}
public partial class MyContext : DbContext, IMyContext
{
public MyContext() { }
public MyContext(DbContextOptions<MyContext> options)
{
}
//left out DBSET<> details
}
public class My1Dao : IMy1Dao
{
private IMyContext context
public My1Dao(IMyContext context)
{
this.context = context
}
}
public class My2Dao : IMy2Dao
{
private IMyContext context
public My2Dao(IMyContext context)
{
this.context = context
}
}
但是我在 MyService 构造函数中得到了两个不同的 MyContext 实例。我知道这一点,因为我在 MyContext Constructora 上有断点,它在那里断了两次。此外,当我从 2 个 DAO 中读取时,它们不会共享返回的集合。这是我需要他们做的。