【问题标题】:Passing parameter to DbContext with DI使用 DI 将参数传递给 DbContext
【发布时间】:2021-02-26 10:02:45
【问题描述】:

我想向 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)
        {           
        
        }

有可能吗? 谢谢

【问题讨论】:

    标签: c# entity-framework asp.net-core


    【解决方案1】:

    你不能通过这种方式将依赖传递给DbContext

    首先,创建一个类:

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

    然后将MyClass作为依赖传递给DbContext

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

    然后将MyClass作为单例注册到ServiceCollection

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

    【讨论】:

      猜你喜欢
      • 2019-02-04
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      • 2019-05-21
      相关资源
      最近更新 更多