同时具有InRequestScope和InTransientScope为Ninject解析为同一类型 [英] Having both an InRequestScope and InTransientScope for Ninject resolving to same type

查看:337
本文介绍了同时具有InRequestScope和InTransientScope为Ninject解析为同一类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Ninject设置,创建一个JobContext解析 InRequestScope()这工作就好了,但是,我在网站要求我一个非常具体的调用通过几个数据库(所有数据库中的按年数据)循环。我不能完全弄清楚发生了什么事情,因为我已经忘记了,JobContext是 InRequestScope ,但代码的最后堵得的的演技怎么样我认为应该。

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.

下面是安装程序

//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();
}



我怎样才能做到这一点?

How can I accomplish this?

推荐答案

这是出现的一个问题是,如果你真的需要JobContext有时在要求范围和瞬态范围内其他案件。似乎有一个设计的味道!试着做以下之前解决这个问题。

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.

this.Bind<IJobContext>().To<JobContext>().InRequestScope().Named("RequestScoped");
this.Bind<IJobContext>().To<JobContext>().InTransientScope().Named("TransientScoped");
kernel.Get<IJobContext>("RequestScoped");



只是另一件事:我succest尝试摆脱Ninject的服务定位类的用法内核和使用依赖注入代替。我会得到一个更好的设计。

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.

这篇关于同时具有InRequestScope和InTransientScope为Ninject解析为同一类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆