[英]Structuremap mvc 5 injecting applicationdbcontext
将Structuremap MVC 5添加到ASP.NET MVC项目。 我希望每个请求都具有一个数据库连接的单例 -我的控制器将共享相同的数据库连接。 我在这里实现存储库模式,需要每个控制器都有其各自存储库的副本。 我知道这是可能的,但我想我正在丢失或误解了某些错误。
我有一个控制器“ 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
类中传递正确的类型吗?
如果您一直在使用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- 和structuremap /
我结束了覆盖默认控制器工厂的工作,没有使用structuremap
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.