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
自动创建ApplicationDbContext
的实例当IConfiguration
和BaseEngine
被创建时,ApplicationDbContext
有什么想法吗?
答案 0 :(得分:2)
为IApplicationDbContext
创建一个公共界面,例如BaseEngine
。把它放在BaseEngine
的构造函数中,而不是具体的类。使BaseEngine
构造函数受到保护。 protected BaseEngine(IApplicationDbContext context)
构造函数应如下所示:
TestEngine
然后,由于BaseEngine
派生自BaseEngine
,而TestEngine
需要构造函数参数,您必须从public TestEngine(IApplicationDbContext context) : base(context)
构造函数中传递它,如:
.format()