我对EF7相对较新,并且听说将DbContext依赖注入到Controller构造函数中是一种使DbContext在给定的Action方法中使用的好方法。但是,在许多情况下不可能进行依赖关系注入(例如,在普通类中访问Db),并且using(VectorDbContext dbContext...)
必须使用该模式。
我遇到了一个问题,using
即通过依赖项注入的上下文无法访问将数据添加到使用该模式创建的DbContext中。DbContext是用于测试的简单InMemory数据库-它不连接任何东西。
这是将实体添加到DbContext的代码,为了进行测试,我在Startup.cs中称其为:
using (ExampleDbContext dbContext= new ExampleDbContext()) {
dbContext.Things.Add(
new Thing() {
Stuff= "something"
});
dbContext.SaveChanges();
}
这是控制器内的访问代码:
public class ExampleController : Controller {
public ExampleController(ExampleDbContext exampleDbContext) {
this.ExampleDbContext= exampleDbContext;
}
public ExampleDbContext ExampleDbContext { get; set; }
public async Task<IActionResult> ExampleAction() {
// new DbContext:
using(ExampleDbContext dbContext = new ExampleDbContext ()) {
var List1 = (await dbContext.Things
.AsNoTracking()
.ToListAsync());
}
// Injected DbContext:
var List2 = (await this.ExampleDbContext.Things
.AsNoTracking()
.ToListAsync());
}
}
单步执行时,List1中有预期的一项,但List2始终为空!
我究竟做错了什么?看来DbContext不同步,依赖注入如何创建DbContext /它来自何处?
编辑:我只是做了一些其他测试,并确认在创建的DbContext中添加的任何实体new
仅在中可见new
,而在Injected DbContext中添加的实体仅在Injected DbContext中可见,这使我相信它们正在连接到不同的实体支持数据库,但我无法确认。
我可能错了,但是我的假设是,当您创建DbContext
in代码的新实例时,您正在使用将基础连接字符串设置为某个默认值的无参数构造函数。但是,注入DIDbContext
可以使用另一个构造函数来解决,该构造函数具有显式传入的不同连接字符串。
这是一个显式指定构造函数参数的Unity配置示例:
<register type="DbContext, [assembly-name]" mapTo="DbContext, [assembly-name]">
<constructor>
<param name="nameOrConnectionString" value="Test"/>
</constructor>
</register>
因此,我将检查您的容器的配置。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句