How to inject a singleton in a custom class constructor and use it | .NET Core 2

I have no extensive experience in testing, but I'm setting up a Singleton instance injection for a class I created. However, I don't know how to call that class. If I do call, I need constructors. If I create an additional empty constructor, the dependencies will appear as null.

I have spent a few days looking for it in the documentation, but it only shows examples of how to inject. I cannot find how to instantiate the class afterwards.

Also, I see some examples, but many of them are using MVC Controllers, which are instantiated automatically by the framework.

Connector.cs
public class Connector
{
    private IConfiguration _configuration;
    public Connector(IConfiguration configuration) {
       _configuration = configuration;
    }

    public Connector() {
    } 

    public string DoSomething() {
      //return Something related to _configuration
    }
}

startup.cs
public void ConfigureServices(IServiceCollection services)
{    
    //Other default config

     services.AddSingleton(new Connector(Configuration));
 }

 HomeController.cs
 public IActionResult Index()
 {

        var x = (new Connector()).DoSomething(); //This will fail as _configuration is not injected
        return View();
 }

How can I call Connector with the injected Configuration? Am I missing any dependency resolving? Am I calling the class incorrectly?

I hope somebody can shed some light on this.

Upvotes: 3

Views: 4500

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

The idea behing DI container is that you don't need to handle object creation in your methods. Your HomeController also doesn't need to know if Connector is actually a singleton or not.

You just inject the dependency to your constructor.
Since you have configured it to be a singleton, DI container will resolve Connector to the same instance every time.

public class HomeController 
{ 
    private readonly Connector _connector;

    public HomeController(Connector connector)
    {
        _connector = connector;
    }

    public IActionResult Index()
    {
        var x = _connector.DoSomething();
        // ...
    }

Upvotes: 3

Related Questions