将结构映射MVC 5添加到ASP.NET MVC项目中。我希望每个请求都有一个数据库连接的单例--我的控制器将共享相同的数据库连接。我在这里实现存储库模式,并需要每个控制器都有其各自存储库的副本。我知道这是可能的,但我想我错过了或者误解了一些错误的东西。
我有一个控制器,“包”,它需要一个"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类中传递正确的类型?
发布于 2014-12-12 17:36:35
如果您一直在使用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/
发布于 2014-12-05 21:38:29
我结束了重写默认控制器工厂,而不使用结构映射
https://stackoverflow.com/questions/27183933
复制相似问题