dimanche 9 janvier 2022

C# - How to inject new instance of dependency to a class which get instantiated once in the app lifetime?

Here is a class which will be instantiated only once through out the lifetime of the application

public class SampleClass //instantiated only once
 {
  public void DoOpertation()//will be called by every incoming request
   {
     var dependentService = new SampleService();
     //do operation on dependentService instance
     ....
   }
  }

Method "DoOpertation" operation will be called many time during the application lifetime.

In "DoOpertation" method I'm instantiating 'SampleService' using 'new' keyword which I don't want to do for the below reasons

  1. It breaks single responsibility principle (SRP) as creating SampleService class instance is not SampleClass's responsibility
  2. Create tight coupling between SampleClass & SampleService classes which makes unit testing harder atleast

I can't use DI container for constructor injection of dependencies as SampleClass get instantiated only once in the application lifetime but where as every invocation of DoOpertation method (which lives inside SampleClass) requires new instance of SampleService class to work properly.

How to inject SampleService class new instance on every invocation of DoOpertation() without using 'new' keyword?

Aucun commentaire:

Enregistrer un commentaire