【问题标题】:Structuremap mvc 5 injecting applicationdbcontextStructuremap mvc 5注入applicationdbcontext
【发布时间】:2014-11-28 07:35:05
【问题描述】:

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

我有一个控制器“Bag”,它需要一个“IBagRepo”

public class BagController : Controller
{
    private readonly IBagRepo repo;

    public BagController(IBagRepo repo)
    {
        this.repo = repo;
    }

    // actions
}

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

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 类中传递了正确的类型?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-mvc-4 structuremap


    【解决方案1】:

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

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

    【讨论】:

    • 感谢杰里米的回复。是否有示例说明如何使用默认生命周期注册 DbContext?
    【解决方案2】:

    我结束了覆盖默认控制器工厂并且没有使用结构映射

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-28
      • 2017-01-01
      • 2011-06-07
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      相关资源
      最近更新 更多