简体   繁体   English

使用 DI 将参数传递给 DbContext

[英]Passing parameter to DbContext with DI

I want to pass an additional parameter to the DBContext, like this我想向 DBContext 传递一个附加参数,如下所示

string myParam="xx";
string con="connenctionstring";
services.AddDbContext<IDbContext, DbContext>(
    options =>options.UseSqlServer(con, myParam)
            );

And in DBContext:在 DBContext 中:


DbContext(DbContextOptions<AppDbContext> options, string myParam)
            : base(options)
        {           
        
        }

Somehow possible?有可能吗? Thanks谢谢

You cannot pass dependency to DbContext in this way.您不能以这种方式将依赖项传递给DbContext

First, create a class:首先,创建一个 class:

class MyClass {
    public string MyProperty { get; set; }
}

Then pass MyClass as a dependency to DbContext :然后将MyClass作为依赖项传递给DbContext

MyDbContext(DbContextOptions<MyDbContext> options, MyClass myParam)
    : base(options)
{           
        
}

Then register MyClass as a singleton to ServiceCollection :然后将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