[英]Use DI in Data Access Layer with ApplicationDbContext (netcore 2.0)
我对DI
( Dependancy Injection
)有一些问题。 我的项目是在netcore 2.0
,几乎没有几层(标准的N层体系结构)。 我正在尝试将EF Core 2
从Presentation 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
,在创建BaseEngine
和ApplicationDbContext
时,该Dependancy Injection
会自动创建ApplicationDbContext
和IConfiguration
实例。 。
有任何想法吗?
为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.