[英]Passing parameter to DbContext with DI
我想向 DBContext 傳遞一個附加參數,如下所示
string myParam="xx";
string con="connenctionstring";
services.AddDbContext<IDbContext, DbContext>(
options =>options.UseSqlServer(con, myParam)
);
在 DBContext 中:
DbContext(DbContextOptions<AppDbContext> options, string myParam)
: base(options)
{
}
有可能嗎? 謝謝
您不能以這種方式將依賴項傳遞給DbContext
。
首先,創建一個 class:
class MyClass {
public string MyProperty { get; set; }
}
然后將MyClass
作為依賴項傳遞給DbContext
:
MyDbContext(DbContextOptions<MyDbContext> options, MyClass myParam)
: base(options)
{
}
然后將MyClass
注冊為 singleton 到ServiceCollection
:
services.AddDbContext<MyDbContext>(options =>options.UseSqlServer(con));
services.AddSingletone(new MyClass { MyProperty = "xx" });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.