一、数据源注入
在最基础的模块中AiTestModule(继承AbpModule)需要注入额外的数据库类
有初始化函数PreInitialize()或者Initialize(),在容器IocManager中需要注入主库和额外库,其他地方亦可以使用此逻辑。
var services = new ServiceCollection();
IdentityRegistrar.Register(services);
services.AddEntityFrameworkInMemoryDatabase();
var serviceProvider = WindsorRegistrationHelper.CreateServiceProvider(iocManager.IocContainer, services);
//注入主数据库
var builder = new DbContextOptionsBuilder<AiDbContext>();
builder.UseInMemoryDatabase(Guid.NewGuid().ToString()).UseInternalServiceProvider(serviceProvider);
iocManager.IocContainer.Register(Castle.MicroKernel.Registration.Component
.For<DbContextOptions<AiDbContext>>()
.Instance(builder.Options)
.LifestyleSingleton());
//注入额外数据库
var builder1 = new DbContextOptionsBuilder<ChemicalDbContext>();
builder1.UseInMemoryDatabase(Guid.NewGuid().ToString()).UseInternalServiceProvider(serviceProvider);
iocManager.IocContainer.Register(Castle.MicroKernel.Registration.Component
.For<DbContextOptions<ChemicalDbContext>>()
.Instance(builder1.Options)
.LifestyleSingleton());
二、数据源数据加入
在继承AiTestModule类的AiTestBase的构造函数中仿写
protected AiTestBase(){
UsingChemicalDbContext(AbpSession.TenantId, context =>
{
new TestChemicalDbDataBuilder(context).Create();
});
}
protected void UsingChemicalDbContext(int? tenantId, Action<ChemicalDbContext> action)
{
using (UsingTenantId(tenantId))
{
//此处是重点,获取容器内的实例数据库
using (var context = LocalIocManager.Resolve<ChemicalDbContext>())
{
action(context);
context.SaveChanges();
}
}
}
在上方的using内的TestChemicalDbDataBuilder获取的数据库句柄中加入指定数据即可
class TestChemicalDbDataBuilder
{
private ChemicalDbContext _context;
public TestChemicalDbDataBuilder(ChemicalDbContext chemicalDbContext)
{
this._context = chemicalDbContext;
}
internal void Create()
{
//准备构建化学库数据
new MrvChemicalDataBuilder(_context).Create();
_context.SaveChanges();
}
}
注意点:
单元测试在调用仓储时,不可使用GetAll()这类非即时数据获取函数,会触发仓储已关闭错误。
暂时测试发现可用的。
FirstOrDefault(it => true)
GetAllList(it => true);