使用ApplicationDbContext(NetCore 2.0)在数据访问层中使用DI



我在 DI( Dependancy Injection(中有一些问题。我的项目在netcore 2.0上,几层(标准的N层体系结构(。我正在尝试将EF Core 2Presentation Layer移动到Data Access Layer,并且在DAL中创建了以下类:

namespace MyProject.Infrastructure.Implementation.MySql.Contexts 
{
    public class ApplicationDbContext : DbContext
    {
        private readonly IConfiguration _configuration;
        public ApplicationDbContext(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        protected override void OnConfiguring(DbContextOptionsBuilder     optionsBuilder)
        {
            optionsBuilder.UseMySql(
                Configuration.GetConnectionString("MySql")
            );
        }
        public DbSet<Test> Test { get; set; }
    }
}

然后我为所有DAL引擎准备了基类:

namespace MyProject.Infrastructure.Implementation.MySql
{
    public class BaseEngine : IBaseEngine
    {
        private readonly ApplicationDbContext _context;
        protected ApplicationDbContext Db => _context;
        public BaseEngine(ApplicationDbContext context)
        {
            _context = context;
        }
    }
}

所以,我的普通引擎应该看起来像这样:

namespace MyProject.Infrastructure.Implementation.MySql
{
    public class TestEngine : BaseEngine
    {
        public List<Test> GetTestList()
        {   
            return Db.Test.ToList();
        }
    }
}

问题是我遇到了错误,base engine需要在构造函数中传递的参数,而我不想手动创建所有实例,我需要以某种方式使用Dependancy Injection自动创建ApplicationDbContextIConfiguration的实例,而BaseEngineApplicationDbContext将会是创建..

有什么想法?

ApplicationDbContext创建一个公共接口,例如IApplicationDbContext。将其放在BaseEngine而不是混凝土类的构造函数中。使BaseEngine构造函数受保护。BaseEngine构造函数应该看起来像:

protected BaseEngine(IApplicationDbContext context)

然后,由于 TestEngine是从 BaseEngine派生的,而 BaseEngine需要一个构造函数参数,因此您必须从TestEngine构造函数传递,例如:

public TestEngine(IApplicationDbContext context) : base(context)