【问题标题】:C#: Create Inherited DbContext, do we have to conduct Dependency Injection again?C#:创建Inherited DbContext,我们是否需要再次进行依赖注入?
【发布时间】:2020-04-30 08:31:53
【问题描述】:

我从另一个 DbContext 创建了一个继承的 DbContext 类。它为某些表执行自定义项,例如在 SaveChanges 之前记录用户信息。

是否需要在 Startup.cs 中再次进行依赖注入?

否则,我们会收到以下错误。

错误:“IPTS.PropertyManagement.Infrastructure.Repositories.CustomPropertyContext”类型的服务未注册。

这第二对代码行解决了问题,只是想知道是否有什么方法可以避免再次重新注入,还是有必要?

services.AddDbContext<PropertyContext>(options =>
   options.UseSqlServer(configuration.GetConnectionString("PMConnection")));
services.AddScoped<DbContext, PropertyContext>();

services.AddDbContext<CustomPropertyContext>(options =>
   options.UseSqlServer(configuration.GetConnectionString("PMConnection")));
services.AddScoped<DbContext, CustomPropertyContext>();

参考自定义类:

public class CustomPropertyContext : PropertyContext
{
    private int _user;

    public CustomPropertyContext()
    {
    }

    public CustomPropertyContext(UserResolverService userService)
    {
        _user = userService.GetUser();
    }

    public void ApplyCreatedBy()
    {
        var modifiedEntities = ChangeTracker.Entries<ICreatedBy>().Where(e => e.State == EntityState.Added);
        foreach (var entity in modifiedEntities)
        {
            entity.Property("CreatedBy").CurrentValue = _user;
        }
    }

    public override int SaveChanges()
    {
        ApplyCreatedBy();
        return base.SaveChanges();
    }
}

顺便说一下,这是一个物业申请系统。

【问题讨论】:

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


    【解决方案1】:

    这第二对代码行解决了问题,只是想知道是否有什么方法可以避免再次重新注入,还是有必要?

    是的,第二对是必需的,因此 DI 知道所有类型都需要注入,正如您在问题下方的评论中所说,有时您会注入 PropertyContext,有时您会使用 CustomPropertyContext。所以这是正确的做法,但您可以简化如下代码:

    var connectionString = configuration.GetConnectionString("PMConnection");
    services.AddDbContext<PropertyContext>(options => options.UseSqlServer(connectionString));
    services.AddDbContext<CustomPropertyContext>(options => options.UseSqlServer(connectionString));
    

    如您所见,我删除了注入 DbContext 基类的行,因为您说您注入的不是DbContext 基类,而是PropertyContextCustomPropertyContext 的特定派生类。您还需要知道,通过多次注册相同类型(此处为DbContext),当您请求DbContext 的实例时,最后一次注册将始终获胜。所以基于下面的代码:

    services.AddScoped<DbContext, PropertyContext>();
    services.AddScoped<DbContext, CustomPropertyContext>();
    

    最后一次注册获胜,当您请求DbContext 的单个实例时,您将始终获得CustomPropertyContext 的实例。

    【讨论】:

      猜你喜欢
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 2020-04-14
      • 2021-10-23
      相关资源
      最近更新 更多