简体   繁体   中英

Passing parameter to DbContext with DI

I want to pass an additional parameter to the DBContext, like this

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

And in DBContext:


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

Somehow possible? Thanks

You cannot pass dependency to DbContext in this way.

First, create a class:

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

Then pass MyClass as a dependency to DbContext :

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

Then register MyClass as a singleton to ServiceCollection :

services.AddDbContext<MyDbContext>(options =>options.UseSqlServer(con));
services.AddSingletone(new MyClass { MyProperty = "xx" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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