C#:创建继承的DbContext,我们必须再次进行依赖注入吗



我从另一个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();
}
}

顺便说一句,这是一个房地产应用系统。

第二对代码行解决了问题,只是想知道是否有任何方法可以避免再次插入,或者是否有必要?

是的,第二对是必要的,这样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的一个实例。

最新更新