Having both an InRequestScope and InTransientScope for Ninject resolving to same type

会有一股神秘感。 提交于 2019-12-08 05:24:48

问题


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?


回答1:


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");

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.



来源:https://stackoverflow.com/questions/4186214/having-both-an-inrequestscope-and-intransientscope-for-ninject-resolving-to-same

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!