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 ();
        }
    }
6
  • "How can I assure that there is no concurrent usage of the service at the same time?" services.AddSingleton also won't do that. Commented Nov 16, 2022 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? Commented Nov 16, 2022 at 11:58
  • 1
    Well it was a interview question that I was asked, so I was wondering how would I do that. Commented Nov 16, 2022 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 stackoverflow.com/questions/519520/… Commented Nov 16, 2022 at 12:17
  • 1
    Yes I think I figured it out. And I can make it trade safe by using lock statement (learn.microsoft.com/en-us/dotnet/csharp/language-reference/…) Commented Nov 16, 2022 at 14:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.