【发布时间】: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