[英]Entity Framework Dependency Injection
I want to know, how the dependency injection is working in EFCore. 我想知道,依赖注入在EFCore中是如何工作的。
I want to change the behavior of the DbSetFinder
to find not only the DbSet<>
or DbQuery<>
members, but finds the members which are inherited from it. 我想更改DbSetFinder
的行为, DbSetFinder
要查找DbSet<>
或DbQuery<>
成员,还要查找从中继承的成员。
The current code is like this: 目前的代码是这样的:
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();
}
This code is found the DbSet<>
in the DbContext
but does not found the members, which are inherited from DbSet<>
. 该代码被发现DbSet<>
中DbContext
但不会发现成员,这是从继承DbSet<>
It means I have to extend the code with Type.IsAssignableFrom(Type)
method, to find the inherited instances as well. 这意味着我必须使用Type.IsAssignableFrom(Type)
方法扩展代码,以便查找继承的实例。
And I want to override in the default IDbSetFinder
with my DbSetFinder
class, the EFCore provide the functionality for it. 我想用我的DbSetFinder
类覆盖默认的IDbSetFinder
, DbSetFinder
为它提供了功能。 Just I don't know where can I do this, and when can I do this. 只是我不知道我在哪里可以做到这一点,我什么时候能做到这一点。
There is a ServiceProvider, and possibility to change the implementation, But I don't know how to do it. 有一个ServiceProvider,可能会改变实现,但我不知道该怎么做。
There is class where the core service dependencies are set: 有一个类,其中设置了核心服务依赖项:
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. 如何在填充默认值之前联系此服务提供商,以及如何更改其实施。
The easiest (and probably intended public) way is to override OnConfiguring
and use DbContextOptionsBuilder.ReplaceService
method: 最简单(也可能是公开的)方法是覆盖OnConfiguring
并使用DbContextOptionsBuilder.ReplaceService
方法:
Replaces the internal Entity Framework implementation of a service contract with a different implementation. 用不同的实现替换服务契约的内部实体框架实现。
eg 例如
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.ReplaceService<IDbSetFinder, CustomDbSetFinder>();
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.