I've got a Ninject setup that creates a JobContext resolver InReq开发者_开发百科uestScope()
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?
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.
精彩评论