依赖项注入具有依赖项注入形式DbContext的类

时间:2018-10-04 16:01:59

标签: c# dependency-injection .net-core

我该如何注入:

private readonly CarModelsController _carModelsController;

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

当CarModelsController看起来像这样:

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

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

注射时需要DbContext吗?是否应该以其他方式完成?去这里的正确方法是什么?我从没学过。

2 个答案:

答案 0 :(得分:3)

我建议您检查将控制器相互注入的选择。

创建一个服务抽象和类,其中包含与Db相关的操作

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

public class DataService: IDataService {
    private readonly ApplicationDbContext context;

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

    //...other members implemented
}

并将其注入您的控制器中。

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
    }

    //...
}

剩下的就是在启动时在组合根目录中向DI容器注册所有依赖项。

假定默认.Net Core DI

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

引用Dependency injection in ASP.NET Core

答案 1 :(得分:0)

您需要将依赖项注入到启动类ConfigureServices方法中。

 public void ConfigureServices (IServiceCollection services) {

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