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

我的DbContext类似于:

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

    ...
}

如何在使用以下配置选项时忽略配置选项:

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

...这样我就可以在构造函数中读取它了通常HasCustomFeature设置值来自DbContext外部的应用程序选项.

推荐答案

有点简化,但AddDbContext基本上注册了DI(source)中的上下文和选项,因此您可以将参数添加到要从DI解析的上下文ctor.因此,最简单的 Select 可能是添加另一个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, using options pattern etc.
serviceCollection.AddSingleton(new MyCustomOptions
{
    HasCustomFeature = true
});
services.AddDbContext<Model.MyDbContext>(...);

Csharp相关问答推荐

是否可以将gltf转换为字节数组,然后将字节数组转换回文件?

.NET最小API映射将T参数列表为[FromQuery]

禁用AutoSuggestBox项目更改时的动画?

为什么EF Core 6会针对null验证Count(*)?

EF Core在请求列表时忽略列,但在按ID获取时包含

如何在Visual Studio代码中更改大括号模式{},用于C#语言

为什么我的ASP.NET核心MVC应用程序要为HTML元素添加一些标识符?

`Task`只有在C#中等待时才会运行吗?

实体框架核心上是否支持使用NPGSQL的字符串聚合?

AsNoTrackingWithIdentitySolutions()似乎不起作用?

为什么任务需要在内部使用ManualResetEventSlim?

具有单一导航属性的EF核心一对多关系

自动映射程序在GroupBy之后使用项目

我想在文本框悬停时在其底部显示一条线

如何使用NumberFormatInfo

如何更改新创建的实例的变量?

如何在C#中正确类型化带有泛型的嵌套类

类/值和日期的泛型方法

是否可以从IQueryable T中获取一个IdentyEntry T>

当`JToken?`为空时?