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

Time:02-13

Given the following classes

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

and

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

I am registering these in my DI container like this (where service is IServiceCollection)

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

Say I inject both of these into 2 different handlers, both within the same scope. How I can ensure that both handlers will use the same object instance?

CodePudding user response:

you used scope life time so every time a client sends a request a new instance will create and for test that you can add a static variable in that classes which keeps its value till the app is running
you can do this and check if they are the same :

     class RWRepository
     {
        public static int staticVariable = 0;
        private int nonStaticVariable = 0;
        public RWRepository()
        {
            nonStaticVariable =   staticVariable;
        }
        public void logTest()
        {
            Console.WriteLine(nonStaticVariable.ToString());
        }
     }

CodePudding user response:

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

Scoped Lifetime works exactly as you describe. You don't need to ensure anything.

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.

Lifetimes:

  • Transient objects are always different. The transient OperationId value is different in the request handler and in the middleware.
  • Scoped objects are the same for a given request but differ across each new request.
  • Singleton objects are the same for every request.
  • Related