我在 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();
}
}
}
问题是我遇到了错误,base engine需要在构造函数中传递的参数,而我不想手动创建所有实例,我需要以某种方式使用Dependancy Injection
自动创建ApplicationDbContext
和IConfiguration
的实例,而BaseEngine
和ApplicationDbContext
将会是创建..
有什么想法?
为ApplicationDbContext
创建一个公共接口,例如IApplicationDbContext
。将其放在BaseEngine
而不是混凝土类的构造函数中。使BaseEngine
构造函数受保护。BaseEngine
构造函数应该看起来像:
protected BaseEngine(IApplicationDbContext context)
然后,由于 TestEngine
是从 BaseEngine
派生的,而 BaseEngine
需要一个构造函数参数,因此您必须从TestEngine
构造函数传递,例如:
public TestEngine(IApplicationDbContext context) : base(context)