由于我是依赖项和IoC的新手,我有一个疑问。如何使用SimpleInjector在嵌套方法中获取DbContext
我有一个领域层(具有业务逻辑)和一个数据层。我们不实施知识库,我们直接使用EF Core。 它是一个类库项目,我们在一个AspNetCore web api,WinForms和另一个框架中使用它。
这个想法是在一个范围内使用相同的上下文。
问题是,我无法在嵌套方法执行中获得相同的上下文,我相信这是因为我完全不理解这个概念,你们能帮我一下吗?
例子:
public class MyTest
{
public void TestContainer()
{
var parentContext = MyContainer.Container.GetInstance<MyContext>();
TestParentAndChildContext(parentContext);
}
private void TestParentAndChildContext(MyContext parentContext)
{
var childContext = MyContainer.Container.GetInstance<MyContext>();
Assert.AreEqual(parentContext, childContext);
}
}
public class MyContainer
{
public static Container Container
{
get { return container ?? (container = RegisterAndVerifyContainer()); }
}
private static Container RegisterAndVerifyContainer()
{
var container = new Container();
container.Options.DefaultScopedLifestyle = new ExecutionContextScopeLifestyle();
container.Register<DbContext, MyContext>(Lifestyle.Scoped);
container.Verify();
return container;
}
}
感谢您分享您的知识。 – Lucas
感谢您分享您的知识。 我还有很多东西需要学习,你认为这是我的最佳选择?我对表示层的访问有限,我们在业务层和数据层下工作,需要在执行一些业务规则时共享相同的上下文。所有项目都是类库。 我怎么能不从我的业务逻辑调用GetInstance并事先构建图形? – Lucas
@Lucus:你不会调用'GetInstance'。您在应用程序的启动路径中注册所有对象(组合根)。并且所有实例都是使用构造函数注入接收的。你建立深刻的物体grapns。 – Steven