jeudi 10 décembre 2020

Injectable singleton service yet not new()able .net core

Using .net-core DI framework, I'm registering my Foo service as singleton:

 services.AddSingleton<IFoo, Foo>();

Yet, I don't want any other developer to create new instance of Foo service:

var storage = new TokenStorage();  // bad practice, not allowed

I know I can make Foo service internally singleton with non-accessible constructor like below:

public class Foo : IFoo 
{
   private static _instance;
   
   protected Foo() {}
   
   public static IFoo GetInstance()
   { 
      return _instance ??= new Foo();
   }
}

But I don't want traditional way of accessing this service using Foo.GetInstance().Bar()

In simple words, I want DI framework to make Foo singleton and yet abandon developers from instantiating it, without using Singleton pattern.

Is there any way or pattern to achieve this?

Aucun commentaire:

Enregistrer un commentaire