让 Ninject 解析为相同类型的 InRequestScope 和 InTransientScope
我有一个 Ninject 设置,可以创建一个 JobContext 解析器 InRequestScope()
这工作得很好,但是,我在网站中有一个非常具体的调用,需要我循环访问几个数据库(所有数据库中的数据(按年份)。我不太明白发生了什么,因为我忘记了 JobContext 是 InRequestScope
,但最后一个代码块没有按照我想象的方式运行。
这是设置,
//Ninject module
Bind<Data.IJobContext>().To<Data.JobContext>().InRequestScope();
//Controller's Initialize
protected override void Initialize(System.Web.Routing.RequestContext requestContext) {
base.Initialize(requestContext);
//set a connection string for the jobContext
this.jobContext = DependencyResolver.Current.GetService<IJobContext>();
jobContext.SetYear(currentYear);
}
因为 JobContext 位于请求范围内,所以每年都会重复使用相同的对象。这是我需要它为 InTransientScope
而不是 InRequestScope
的唯一实例。
//Special function
foreach (int year in ActiveYears) {
jobContext = DependencyResolver.Current.GetService<IJobContext>();
jobContext.SetYear(year);
DoSomething();
}
我怎样才能做到这一点?
I've got a Ninject setup that creates a JobContext resolver InRequestScope()
This works just fine, however, I have a very specific call in the Website that requires me to loop through a few databases (all the data in databases by year). I couldn't quite figure out what was going on because I had forgotten that the JobContext was InRequestScope
but the last block of code was not acting how I thought it should.
Here is the setup
//Ninject module
Bind<Data.IJobContext>().To<Data.JobContext>().InRequestScope();
//Controller's Initialize
protected override void Initialize(System.Web.Routing.RequestContext requestContext) {
base.Initialize(requestContext);
//set a connection string for the jobContext
this.jobContext = DependencyResolver.Current.GetService<IJobContext>();
jobContext.SetYear(currentYear);
}
Since JobContext is in request scope it keeps reusing the same object for each year. This is the only instance where I need it to be InTransientScope
rather than InRequestScope
.
//Special function
foreach (int year in ActiveYears) {
jobContext = DependencyResolver.Current.GetService<IJobContext>();
jobContext.SetYear(year);
DoSomething();
}
How can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
出现的一个问题是,您是否确实有时需要在请求范围内使用 JobContext,而在其他情况下则需要在瞬态范围内使用 JobContext。似乎有一股设计的味道!在执行以下操作之前尝试解决此问题。
如果您确实想按照您描述的方式执行此操作,则必须指定两种不同的命名绑定,一种在瞬态中,一种在请求范围中,然后它们通过名称获取它们。
还有一件事:我会成功地尝试摆脱 Ninject 内核的 ServiceLocator 类型的使用,并改用依赖注入。我会得到更好的设计。
One question that comes up is if you really need the JobContext in request scope sometimes and in other cases in transient scope. There seems to be a design smell! Try to fix this before doing the the following.
If you really want to do it the way you described you have to specify two different named bindings one in transient and one in request scope and them get them by name.
Just another thing: I'd succest to try to get rid of the ServiceLocator kind usage of the Ninject kernel and use dependency injection instead. I'll get a better design.