如何使用 StructureMap、MVC 5 和 WebApi 2 注册每个请求依赖项?

How to register per request dependencies using StructureMap, MVC 5, and WebApi 2?

我有一个 Mvc5-WebApi2 应用程序,它通过 StructureMap.Mvc5 和 StructureMap.WebApi2 Nuget 包使用 StructureMap 进行依赖注入。我想为 MVC 和 Web 控制器注册我的 EF 6 DbContext 和 HttpContext 生命周期。有人能给我一个关于如何为 MVC 和 WebApi 实现这一点的简洁解释吗?通常,如何在每个请求容器中注册某些依赖项,而在父容器中注册其他依赖项?

HttpContext 绑定生命周期的推荐方法是利用 StructureMap 的 nested containers

这通过配置 StructureMap 容器然后创建容器的嵌套实例并将其存储在请求开始时的 HttpContext 中并在整个 HttpRequest 中使用该容器来实现,然后在结束 (see here for the source code).

您可以自行设置 (see this blog post on how to do this),也可以使用这两个 NuGet 包为您完成:

StructureMap.MVC5 and StructureMap.WebApi.

设置完成后,您就可以注册您的 DbContext 以正常方式:

this.For<DbContext>.Use(new DbContext(connectionString));

希望对您有所帮助。如果您有任何问题,我会尽力提供帮助。