繁体   English   中英

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

[英]Use DI in Data Access Layer with ApplicationDbContext (netcore 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 ,在创建BaseEngineApplicationDbContext时,该Dependancy Injection会自动创建ApplicationDbContextIConfiguration实例。 。

有任何想法吗?

ApplicationDbContext创建一个公共接口,例如IApplicationDbContext 将其放在BaseEngine的构造函数中,而不是具体的类中。 使BaseEngine构造函数受保护。 BaseEngine构造函数应如下所示:

protected BaseEngine(IApplicationDbContext context)

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

public TestEngine(IApplicationDbContext context) : base(context)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM