I have a class that might need a service or not, previously registered through dependency injection, depending on the user needs.
He instanciate my class via the static method GetInstance(bool), and if bool is set to true then I need to call a constructor based on dependency injection. How to achieve this?
public class MyClass {
  private MyClass() {
    // ...
  }
  private MyClass(MyService env) {
    // ...
  }
  public static MyClass GetInstance(bool serviceIsNeeded) {
     if (serviceIsNeeded) {
         /* How to realize the following ?
          * if (!ServiceRegistered<MyService>())
          *     throw new ServiceNotFoundException(...);
          * return InstanciateWithDependencyInjection(typeof(MyClass));
         */
     }
     else
         return new MyClass();
  }
}
For instance in Java, you put an @Inject tag on top of your constructor, and then you instanciate your class like this: MyClass myClass = getInjector(getContext()).getInstance(MyClass.class)
I'm looking for the same concept in C# and ASP.NET Core 2.
 
     
     
    