Structuremap mvc 5 注入应用程序数据库上下文



将 Structuremap MVC 5 添加到 ASP.NET MVC 项目中。我希望每个请求都有一个数据库连接的单一实例 - 我的控制器将共享相同的数据库连接。我在这里实现存储库模式,需要每个控制器都有其各自存储库的副本。我知道这是可能的,但我认为我错过或误解了错误的东西。

我有一个控制器"Bag",需要一个"IBagRepo"

public class BagController : Controller
{
    private readonly IBagRepo repo;
    public BagController(IBagRepo repo)
    {
        this.repo = repo;
    }
    // actions
}

我的第一次尝试是在控制器约定中挂接单例数据库连接,因为我假设它被调用过一次

public class ControllerConvention : IRegistrationConvention {
    public void Process(Type type, Registry registry) {
        if (type.CanBeCastTo<Controller>() && !type.IsAbstract) {
            // Tried something like
            registry.For(type).Singleton().Is(new ApplicationDbContext()); // this
            registry.For(type).LifecycleIs(new UniquePerRequestLifecycle());
        }
    }
}

但很明显,这不是进行此更改的正确文件。我进入了安装 nuget 包时自动生成的注册表类,并尝试摆弄它。

    public class DefaultRegistry : Registry {
    #region Constructors and Destructors
    public DefaultRegistry() {
        Scan(
            scan => {
                scan.TheCallingAssembly();
                scan.WithDefaultConventions();
                scan.With(new ControllerConvention());
            });
        // httpContext is null if I use the line below
        // For<IBagRepo>().Use<BagRepo>().Ctor<ApplicationDbContext>().Is(new ApplicationDbContext());
    }
    #endregion
}

我还没有在这里看到这样的问题。我在DefaultRegistry课上是否通过了正确的类型?

如果你一直在使用 StructureMap.MVC5 nuget: https://www.nuget.org/packages/StructureMap.MVC5/,你想要的实际上是默认行为。 只要您的 DbContext 已注册到默认生命周期,该包就会为每个 http 请求使用嵌套容器,从而有效地将 DbContext 的范围限定为工作单元范围的 HTTP 请求。

与 MVC 和 EF 不同的工具,但我在这篇博文中描述了 FubuMVC + RavenDb 带 StructureMap 的类似机制:http://jeremydmiller.com/2014/11/03/transaction-scoping-in-fubumvc-with-ravendb-and-structuremap/

我结束了覆盖默认控制器工厂并且不使用结构图

最新更新