我想知道依赖注入(inject)在 EFCore 中是如何工作的。
我想改变 DbSetFinder
的行为不仅要找到 DbSet<>
或 DbQuery<>
成员,但找到从它继承的成员。
目前的代码是这样的:
private static DbSetProperty[] FindSets(Type contextType)
{
var factory = new ClrPropertySetterFactory();
return contextType.GetRuntimeProperties()
.Where(
p => !p.IsStatic()
&& !p.GetIndexParameters().Any()
&& p.DeclaringType != typeof(DbContext)
&& p.PropertyType.GetTypeInfo().IsGenericType
&& (p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)
|| p.PropertyType.GetGenericTypeDefinition() == typeof(DbQuery<>)))
.OrderBy(p => p.Name)
.Select(
p => new DbSetProperty(
p.Name,
p.PropertyType.GetTypeInfo().GenericTypeArguments.Single(),
p.SetMethod == null ? null : factory.Create(p),
p.PropertyType.GetGenericTypeDefinition() == typeof(DbQuery<>)))
.ToArray();
}
此代码是在 DbSet<>
中找到的在DbContext
但没有找到继承自 DbSet<>
的成员.
这意味着我必须用 Type.IsAssignableFrom(Type)
扩展代码方法,也可以找到继承的实例。
我想覆盖默认的 IDbSetFinder
和我的 DbSetFinder
类,EFCore 为其提供功能。只是我不知道在哪里可以这样做,什么时候可以这样做。
有一个 ServiceProvider,并且可以更改实现,但我不知道该怎么做。
有设置核心服务依赖的类:
public virtual EntityFrameworkServicesBuilder TryAddCoreServices()
{
TryAdd<IDbSetFinder, DbSetFinder>();
TryAdd<IDbSetInitializer, DbSetInitializer>();
TryAdd<IDbSetSource, DbSetSource>();
TryAdd<IDbQuerySource, DbSetSource>();
...
How Can I reach this service provider before it fills with default values, and how can I change the implementation of it.
最佳答案
最简单(并且可能是公开的)方法是覆盖 OnConfiguring
并使用 DbContextOptionsBuilder.ReplaceService
方法:
Replaces the internal Entity Framework implementation of a service contract with a different implementation.
例如
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.ReplaceService<IDbSetFinder, CustomDbSetFinder>();
// ...
}
关于c# - Entity Framework 依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54052609/