1

So right now I am using this line of code to register a service on my app:

services.AddSingleton<IDefaultService, DefaultService>();

I was wondering if there is a way to "mimic" this behavior without using Dependency Injection extension? And if there is how?

So I know that static classes are created once when the app is built/run, so this is a behavior I want. How can I assure that there is no concurrent usage of the service at the same time?

public static class DefaultServiceRegistry {
        public static DefaultService DefaultServiceInstance { get; set; }

        static DefaultServiceRegistry ()
        {
            DefaultServiceInstance = new DefaultService ();
        }
    }
  • "How can I assure that there is no concurrent usage of the service at the same time?" services.AddSingleton also won't do that. – Klamsi Nov 16 '22 at 11:58
  • 2
    This is a really odd question. First of all, why do you want to do this? It seems like you are going backwards. Secondly, if you are worried about concurrent access, then maybe it shouldn't be a singleton in the first place? – DavidG Nov 16 '22 at 11:58
  • 1
    Well it was a interview question that I was asked, so I was wondering how would I do that. – Dmytro Golovin Nov 16 '22 at 12:06
  • I would say you can use a static class with a static constructor to initialize it as a lazy one, but a container is a better solution, check more info here https://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern – DonMiguelSanchez Nov 16 '22 at 12:17
  • 1
    Yes I think I figured it out. And I can make it trade safe by using lock statement (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/statements/lock) – Dmytro Golovin Nov 16 '22 at 14:34
  • Hi @DmytroGolovin , like you said you can use the lock statement in your class methods to make it threat safe, but also you must be aware that your class properties and fields will be shared to everyone with access to that class. – MarchalPT Nov 16 '22 at 15:20

0 Answers0