DbContext - 传递自定义配置选项

问题描述 投票:0回答:1

我有带有实体框架的 .NET Core 6 Web 应用程序。

我的 DbContext 是这样的:

public class MyDbContext : DbContext
{
    public MyDbContextDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
        this.HasCustomFeature = // How to set it from configuration options
    }

    ...
}

使用时如何通过配置选项传递

HasCustomFeature

services.AddDbContext<Model.MyDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

...所以我可以在构造函数中读取它?一般来说,

HasCustomFeature
设置值来自我的 DbContext 外部的应用程序选项。

c# entity-framework asp.net-core dependency-injection .net-6.0
1个回答
0
投票

可能最简单的选择是添加另一个 ctor 参数并在 DI 中注册相应的服务:

public class MyCustomOptions
{
    public bool HasCustomFeature { get; set; }
}

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> opts, MyCustomOptions myOpts):base(opts)
    {
         this.HasCustomFeature = myOpts.HasCustomFeature;
    }
}

以及报名:

// sample registration, can be bound from config, etc.
serviceCollection.AddSingleton(new MyCustomOptions
{
    HasCustomFeature = true
});
services.AddDbContext<Model.MyDbContext>(...);
© www.soinside.com 2019 - 2024. All rights reserved.