Matias Miraglio
Matias Miraglio

Reputation: 553

How to instantiate an object with a reference to another object that depends on DI ASP.NET core 2.0?

I have a controller's constructor in which I want to instantiate an object that gets access to the repository via dependency injection.

like this:

ContactController.cs: I get an error because I don't pass an IContactRepository

private ContactOperationsFacade contactOperator;

ContactController(){
    contactOperator = new ContactOperationsFacade(//I want to use DI here);
}

ContactOperationsFacade.cs:

private readonly IContactRepository contactRepository;

public ContactOperationsFacade(IContactRepository contactRepositor){
    this.contactRepository = contactRepository;
}

How can I instantiate this ContactOperationsFacade object in the controller's constructor still using DI for the repository?

Upvotes: 0

Views: 1741

Answers (2)

Nkosi
Nkosi

Reputation: 247088

ContactController should follow The Explicit Dependencies Principle

Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.

Also classes should depend on abstractions and not coupled to concretions.

So assuming something like

public class ContactOperationsFacade: IContactOperationsFacade { //<-Note interface/contract

    private readonly IContactRepository contactRepository;

    public ContactOperationsFacade(IContactRepository contactRepositor){
        this.contactRepository = contactRepository;
    }

    //...
}

The controller should depend on the abstraction that the facade is derived from

public class ContactController: Controller {

    private readonly IContactOperationsFacade contactOperator;

    public ContactController(IContactOperationsFacade contactOperator){
        this.contactOperator = contactOperator;
    }

    //...

}

And assumes that all the interfaces and implementations are registered with the DI container.

services.AddScoped<IContactOperationsFacade, ContactOperationsFacade>();

once all dependencies are registered the service provider should resolve them when activating the controller.

Upvotes: 1

stephanV
stephanV

Reputation: 183

In asp.net core you can do DI chaining as long as scopes allow it. So if A depends on B and the controller wants A you just add both A and B to the di container (ConfigureServices part of your code) and the container will figure it out.

Read more here https://learn.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1

Upvotes: 2

Related Questions