'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



Solution 1:[1]

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)
{           
    //* Intentionally empty            
}

Then register MyClass as a singleton to ServiceCollection:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1