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

时间:2018-02-12 16:34:33

标签: c# dependency-injection .net-core asp.net-core-2.0 ef-core-2.0

DIDependancy 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();
        }
    }
}

问题是我收到错误,BaseEngine需要在构造函数中传递参数而我不想手动创建所有实例,我需要以某种方式使用Dependancy Injection自动创建ApplicationDbContext的实例当IConfigurationBaseEngine被创建时,ApplicationDbContext

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

IApplicationDbContext创建一个公共界面,例如BaseEngine。把它放在BaseEngine的构造函数中,而不是具体的类。使BaseEngine构造函数受到保护。 protected BaseEngine(IApplicationDbContext context) 构造函数应如下所示:

TestEngine

然后,由于BaseEngine派生自BaseEngine,而TestEngine需要构造函数参数,您必须从public TestEngine(IApplicationDbContext context) : base(context) 构造函数中传递它,如:

.format()