![](/img/trans.png)
[英]How can I use a DbContext from a different assembly for my migrations?
[英]How can i inejct only one intance of my DbContext per request in my controllers?
我的控制器需要兩種類型的服務,並且都需要具有相同的dbcontext接口,
public class MyController : Controller
{
protected readonly ISomeService _some;
protected reaonly IUnitOfWork _unitOfWork
public MyController(IUnitOfWork unitOfWork, ISomeService some)
{
_some = some;
_unitOfWork = unitOfWork
}
//這是我的配置
services.AddDbContext<MyContext>(x =>
{
x.UseSqlServer(Configuration.GetConnectionString("coon"));
});
從文檔 :
實體框架上下文
應使用范圍生存期將實體框架上下文添加到服務容器中。 注冊數據庫上下文時,通過調用AddDbContext方法自動處理。 使用數據庫上下文的服務也應使用作用域生存期。
因此AddDbContext會將其添加為作用域生命周期。
您需要確保控制器/或其他使用它的地方也作為Scoped項目添加到DI中。
每個請求創建一次范圍生命周期服務。
我發現Issuse我的問題是我使用AsyncSaveChanges insted SaveChanges,但我的服務得到了相同的instace謝謝大家:)!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.