0

I have an interface:

public interface Irepos 
{
    string somefunction();
}

Then the class I want to use:

public class repos : Irepos
{
    string somefunction()
    {
        return "function called";
    }
}

Registered as singleton in startup.cs:

services.AddSingleton<Irepos, repos>();

Now I can use it like this in my controller class:

public class controller 
{
    private readonly Irepos interfaceRepos;
    
    public ValuesController(Irepos reposInerface)
    {
        interfaceRepos = reposInerface;
    }

    interfaceRepos.somefunction();
}

Now my question is: can I use the same instance of the same repos class in a different class or different controller? Say:

public class AnotherController
{
    private readonly Irepos interfaceRepos;
        
    public ValuesController(Irepos reposInerface)
    {
        interfaceRepos = reposInerface;
    }
    
    interfaceRepos.somefunction();
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
thou_mayest
  • 15
  • 1
  • 6

1 Answers1

0

By definition, only one instance of a singleton exists.

Your controllers can execute in parallel.

If the object in question is thread-safe (for example, it might contain lookup tables or other read-only values), it's reasonable and probably desirable to use a singleton.

If the object isn't thread-safe, scoped lifetime is likely to be the appropriate choice.

Eric J.
  • 147,927
  • 63
  • 340
  • 553