如何确保将 2 个注入接口实例化为同一对象实例

How to ensure 2 injected interfaces are instantiated as the same object instance

给出以下 类

public class RWRepository<TEntity, TEntityId> : IRWRepository<TEntity, TEntityId>

internal sealed class EagerLoadingRWRepository<TEntity>
    : RWRepository<TEntity, Guid>
    , IEagerLoadingRWRepository<TEntity>

我正在像这样在我的 DI 容器中注册这些(serviceIServiceCollection

services.AddScoped(typeof(IRWRepository<,>), typeof(RWRepository<,>));
services.AddScoped(typeof(IEagerLoadingRWRepository<>), typeof(EagerLoadingRWRepository<>));

假设我将这两个注入到 2 个不同的处理程序中,都在同一范围内。我如何确保两个处理程序将为每个注入的接口使用相同的对象实例?

即如果两个接口都被注入,那么两者应该使用相同的 EagerLoadingRWRepository 实例,它继承自 RWRepository

How I can ensure that both handlers will use the same object instance?

Scoped Lifetime 的工作原理与您描述的完全一样。您无需确保任何事情。

Microsoft Docs

https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection#scoped

For web applications, a scoped lifetime indicates that services are created once per client request (connection). Register scoped services with AddScoped.

In apps that process requests, scoped services are disposed at the end of the request.

生命周期:

  • 瞬态对象总是不同的。请求处理程序和中间件中的瞬态 OperationId 值不同。
  • 给定请求的作用域对象相同,但每个新请求都不同。
  • 每个请求的单例对象都是相同的。

这对于 MS.DI(ASP.NET Core 的 built-in DI 容器)来说会非常麻烦,因为它需要您明确地进行每个关闭注册。

例如:

services.AddScoped<IEagerLoadingRWRepository<Person>, EagerLoadingRWRepository<Person>>();
services.AddScoped<IRWRepository<Person, Guid>>(
    c => (IRWRepository<Person, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Person>>());

services.AddScoped<IEagerLoadingRWRepository<Order>, EagerLoadingRWRepository<Order>>();
services.AddScoped<IRWRepository<Order, Guid>>(
    c => (IRWRepository<Order, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Order>>());

services.AddScoped<IEagerLoadingRWRepository<Shipment>, EagerLoadingRWRepository<Shipment>>();
services.AddScoped<IRWRepository<Shipment, Guid>>(
    c => (IRWRepository<Shipment, Guid>)c.GetRequiredService<IEagerLoadingRWRepository<Shipment>>());