I'm writing my first MVC (v3) app and I think I've organized my controllers incorrectly. I'd appreciate some guidance/advice.
This all came up because I'm using Ninject for dependency injection, and wanted it to create only one instance of my concrete DataRepository for each "request". That's easy enough to do by specifying InRequestScope() in the Ninject bindings...but after doing that I still kept seeing multiple instances of my DataRepository being created.
After scratching my head for quite a while I started monitoring the BeginRequest event in the MvcApplication class (in the global.asax file). Lo and behold, what I had thought of as a single "request" -- e.g., a single postback from the browser -- was in fact yielding multiple consecutive requests. Ninject, as per the InRequestScope() declaration, dutifully created one instance of my DataRepository for each of those requests.
Unfortunately, that's not quite what I want. What I'd like is one instance of the DataRepository being created for that single browser-initiated "request". I don't see how I can do this via Ninject. I know I could specify InSingletonScope(), but while that will utilize one DataRepository instance for the "request", the instance will hang around until the webapp restarts. Which causes me all sorts of Entity Framework caching issues.
In monitoring the BeginRequest events, it looks to me like every time a different controller is called a new request is generated. In hindsight this makes sense, but it's not consistent with my app's design. For example, I have certain common action methods that various other action methods chain to (I did that rather than duplicate the same code and views in different controllers).
All of which leads me to wonder about the following: if I want to minimize the number of times my DataRepository is instantiated I have to minimize the number of times one controller chains to another controller. Which would seem to mean that my action methods need to be consolidated, and possibly duplicated in multiple controllers.
That seems... odd. If it's the right way to do things, okay, I can live with it. But I'd love to learn that I'm missing something else in the way of designing MVC apps :). Should I, for example, centralize those common functions in a service layer, and only instantiate it once per request? If that's a dumb question, apologies; I don't really understand the concept of a service layer.