繁体   English   中英

使用 DI 将参数传递给 DbContext

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM