如何使用工厂模式实现每个请求/线程的数据上下文
使用此 示例项目 作为指导,我正在设置一个新项目。我的项目将遵循相同的基本架构,只是除了 mvc 项目之外,我还将有一个 wcf Web 服务项目(或者可能是 servicestack.net),
而不是像示例中那样使用 Unity 进行 DI,而是使用 Ninject。目前,我按如下方式配置 Ninject,以便每个 Web 请求仅实例化一个数据库工厂实例(因此每个请求实例化一个数据上下文类(首先使用 EF 4.1 代码顺便说一句))
kernel.Bind<IDatabaseFactory>()
.To<DatabaseFactory>()
.InScope(ctx => HttpContext.Current);
我很好奇这种方法是否足够?或者让工厂类处理每个 http 请求的数据上下文的实例化会更好(如果我将来为非基于 Web 的前端设计,可能还有每个线程)?如果是这样,有没有什么例子可以说明如何解决这个问题?
或者有没有更好的解决方案来处理这个问题?
Using this sample project as a guideline, I am setting up a new project. My project will follow the same basic architecture, only in addition to an mvc project, I will also have a wcf web service project(or possibly servicestack.net)
Instead of using Unity for DI as in the sample, I am using Ninject. Currently I am configuring Ninject as follows to only instantiate one instance of Database factory per web request(and thus one datacontext class per request (using EF 4.1 code first btw))
kernel.Bind<IDatabaseFactory>()
.To<DatabaseFactory>()
.InScope(ctx => HttpContext.Current);
I am curious if this method is sufficient? Or would it be better to let the factory class handle the instantiation of datacontext per http request(and possibly per thread if I were design for non web based front-ends in the future)? If so, are there any examples out there of how to go about this?
Or is there a completely better solution to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用
.InRequestScope()
而不是.InScope(ctx => HttpContext.Current)
。它确保根据实例是通过 WCF 还是通过 ASP.NET MVC 请求来使用适当的范围。不幸的是,要充分利用这一点,您必须使用 http://teamcity.codebetter.com< 中当前的持续集成版本/a> .另请参阅https://github.com/ninject/ninject.extensions.wcf
https://github.com/ninject/ninject.web.mvc
You should use
.InRequestScope()
instead of.InScope(ctx => HttpContext.Current)
. It ensures that the appropriate scope is used depending on whether the instance is requested via WCF or via ASP.NET MVC. Unfortunately to take full advantage of this you'll have to use the current continous integration builds from http://teamcity.codebetter.com . See alsohttps://github.com/ninject/ninject.extensions.wcf
https://github.com/ninject/ninject.web.mvc