LittleMygler
LittleMygler

Reputation: 632

Dependency inject a class that has a dependency injection form DbContext

How can I inject this:

private readonly CarModelsController _carModelsController;

public AdminController(CarModelsController carModelsController)
{
    _carModelsController = carModelsController;
}

When the CarModelsController looks like this:

[ApiController]
    public class CarModelsController : ControllerBase
    {
        private readonly ApplicationDbContext _context;

        public CarModelsController(ApplicationDbContext context)
        {
            _context = context;
        }

I need to have the DbContext when I inject it? Should it be done in another way? What's the correct way to go here? I've never learned this.

Upvotes: 0

Views: 191

Answers (2)

rykamol
rykamol

Reputation: 1147

You nedd to inject your dependencies into the startup class ConfigureServices method.

 public void ConfigureServices (IServiceCollection services) {

        services.AddScoped<DbContext, Your_Project_DbContext> ();
        services.AddScoped<Your_Interface, Your_Concrete_Class> ();
    }

Upvotes: 0

Nkosi
Nkosi

Reputation: 246998

I would advise you review the choice of injecting controllers into each other.

Create a service abstraction and class that holds the Db related actions

public interface IDataService {
    //...expose desired members
}

public class DataService: IDataService {
    private readonly ApplicationDbContext context;

    public DataService(ApplicationDbContext context) {
        this.context = context;
    }

    //...other members implemented
}

and inject that into your controllers.

public class AdminController: ControllerBase {    
    private readonly IDataService service;

    public AdminController(IDataService service) {
        this.service = service
    }

    //...
}

[ApiController]
public class CarModelsController : ControllerBase  
    private readonly IDataService service;

    public CarModelsController(IDataService service) {
        this.service = service
    }

    //...
}

All that is left is to register all dependencies with the DI container at startup in the composition root.

Assuming default .Net Core DI

services.AddDbContext<ApplicationDbContext>(...);
services.AddScoped<IDataService, DataService>();

Reference Dependency injection in ASP.NET Core

Upvotes: 3

Related Questions