RavenDB session per request with MVC3 and Ninject using repository model - asp.net-mvc-3

I am looking for some advice on the correct mechanism to use for getting a RavenDB IDocumentSession into my repositories in a true session-pr-request behaviour.
This is a greenfield MVC3 application, and I've gotten Ninject / Ninject.MVC3 using NuGet. RavenDB is running on an external server (i.e. non-embedded).
I've set up the Ninject module to return the right repositories, and also a session per request for them.
However - is it true that MVC3 will instantiate the controller for each action method? In that case, I can just allow MVC3/Ninject to inject my repositories and the sessions they need, no problem.
However, if a controller is reused across several requests, this might not work, as the repository hanging around from a previous request might now employ a session that is old and discarded.
I have looked at a few ways to do this - the above is the basic one. I have also tried to do something like an ActionFilterAttribute that gets a new session from the IoC container at the start of each request - but in that case, where should I put it?
Should my repository have a Session property it uses that actually gets the current session from the container each time? This would add coupling between the repository implementation and the IoC container, but otherwise should work I guess.
What is the proper way to do this? How are the cool kids doing it? Any help would be highly appreciated!

Unless you are doing something really funny with your controller factory, each controller instance will be used for a single requests.
Controllers are not thread safe and will not usually survive beyond a single request.

I've written a comprehensive blog post about using Ninject's InRequestScope so that IDocumentSession is injected once per request. Ninject is great at managing scope for you.
http://www.dalsoft.co.uk/blog/index.php/2012/04/12/mvc-get-ravendb-up-and-running-in-5-minutes-using-ninject/

I think that you should avoid going on with Controllers.
It may help sometime:
If session state is disabled we should no longer try to use the Session Property on the Controller as it will be null. Turning off session state and using the Session Property will give you the dreaded “object reference not set to an instance of object” error.

Related

Using correctly the #Scope annotation is Spring 3 web application

I recently readed carefully about the spring mvc 3 beans scope, specifically the web ones(session, request and global session) and i have some doubdts:
If i have a controller, why should i annotate him with other scope aside of singleton? I mean, the controllers are supossed to handle the requests and instantiate the view resources of all the app, so why give them a, for instance, session scope? what is the advantage of do that?
Is advisable making the services layer session scoped?
And finally, is there any convention or good practices that dictates where and when is more convenient the use each one of the web scopes? If there is, can somebody provides me the link or information about it? Not necessary convention or good practices, also your experience about it.
Thanks very much.
I mean, the controllers are supossed to handle the requests and
instantiate the view resources of all the app, so why give them a, for
instance, session scope?
In an average web application, you have various objects that exist on a per-session basis. Example can be user profile, or some kind of cabinet, or wallet, etc.
To be able to use those objects in service, every time you should get from session, and pass through the service chain. Instead of doing this, of course it is better to have those available in your service, without a need to pass it explicitly.
Really good example (in practice) you can find here.
An ideal practical example of request scope bean is HttpServletRequest, which should be unique obviously for each request, therefore it is request scoped and created for each request.
From my experience, without any explicit need for a case, you don't need to bother yourself with changing scopes. It is not without reason that default scope is Singleton, it is by purpose - because in most of the applications and basic scenarios you need beans as singleton. However as your main concern was with Session and Request scopes, the above examples are cases which you need often in web application.

Per-Request DependencyResolver in Web API

In MVC, a ModelValidatorProvider is instantiated and called to validate a model on each request. This means that in a DI environment, it can take dependencies on objects scoped within a single request, such as a Unit of Work or Database context. In Web API, this appears to have been significantly changed. Instead of being instantiated per-request, the ModelValidatorProvider appears to be long-lived and instantiated within the application startup. The WebAPI then caches the results from the ModelValidatorProvider per-type, meaning that the ModelValidator cannot take any dependencies from DI.
I am trying to implement my ModelValidator to use a factory using a Service Locator (please, no automatic 'anti-pattern' comments!). This would allow me to construct an internal validator object within each request, which would be able to take dependencies from the container. However, I cannot get hold of a Dependency Resolver or container scoped to the current request from within this ModelValidator which is essentially scoped as a Singleton. I've tried to use GlobalConfiguration.Configuration.DependencyResolver, but this only returns globally-scoped services (from the root scope, also mentioned here)
I'm working in Autofac, so an autofac-specific solution would be suitable (e.g. MVC has AutofacDependencyResolver.Current, which internally uses DependencyResolver.GetService). There is no equivalent available in the WebAPI integration, presumably because of the reason mentioned above where the global DependencyResolver only returns globally-scoped services.
The reason I'm trying to do this (as well as for my own use) is to implement the Web API integration for FluentValidation, which currently does not exist. There have been two attempts so far, but neither of these handle the Dependency Injection issue and instead result in a single static ModelValidator.
Things I've tried so far:
Using GlobalConfiguration.Configuration.DependencyResolver (returns objects from the root scope)
Taking a dependency on Func<IComponentContext> (always returns the root context)
In an answer which has since been removed, it was suggested to remove IModelValidatorProvider service from the Web API config. This had to be done using reflection since the interface and the implementing classes are all defined as internal, but it did make the validators work better (because the ModelValidator was constructed per request). However, there is a significant performance hit to doing it this way due to the use of reflection to check for validators on the model and every property it has, so I don't want to take this option.
Filip W's answer suggests using HttpRequestMessage to get the Dependency Scope, but I've not found anything such as HttpRequestMessage.Current which would provide access to this object from within a long-lived object - if that could be achieved I believe everything would fall into place.
To get current dependency scope, you have to use (surprise, surprise :) GetDependencyScope() of the current HttpRequestMessage (more about which you can read up on MSDN) instead of GlobalConfiguration.
I blogged about Web API per-request dependency scope a while ago - that should be helpful.

Is it ok to call SignalR's IConnectionManager inside my mvc3 controllers?

I'm on an MVC3 project and I am using snap structuremap for my dependecy injection. Everything was in-place, except when I started using SignalR where I can't seem to implement my DI like I have on my controllers. I've been googling about implementing structuremap DI on SignalR for days now, but haven't found a strong sample on how to do this. Seems like everyone that are using SignalR are using Ninject.
My goal is to have conditional statements (which requires me to inject services) inside my Hub before calling my client methods, but I had no success on this.
I didn't want this thing to delay my development so I researched for alternative ways, then I found out that I can actually call my client methods from my controllers using the following codes:
IConnectionManager connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
dynamic clients = connectionManager.GetClients<MyHub>();
clients.myClientScript();
This works for me, but I'm not sure if this is a good approach - especially that I am using dependency injection.
So my question is: Is it ok to keep calling this inside my controller? Do you have a better approach?
Thanks
There is no reason you cannot send information to connected clients from your controller using SignalR however the current client will not see this information (due to not being connected during a post).
That said, getting Structuremap into SignalR is actually pretty easy. You can see exactly how to accomplish this in my answer here: https://stackoverflow.com/a/9866374/701062.

Scope confusion regarding session beans, proxies, and singletons in a Spring 3 managed JSF app

This seems like it's basic Spring 101 stuff, but I can't seem to find the correct way to do this. The situation is as follows; in my web app there is a single entry point which is a controller that handles users coming from an outside system. The transfer is just a POST request with a bunch of associated information pertaining to that user. Apon entry, I need to create a new User bean and load it with that users information. Additionally, when the user hits a view which triggers some service, I need for that service to be able to access the appropriate User bean instance.
The first way to do this that came to mind was to have a UserManager service which would create a new instance of User, fill it w/ data, and then register it in the Spring container with the username as the bean name. Then when a service is invoked, the service would do something like Factory.getBean(username) to find the appropriate User instance. The problem I see here is that I'm losing the link between the user & which User bean belongs to them. Additionally, I'd like to avoid having the user carry the bean around in the session if at all possible. Is this where I am supposed to be using Spring AOP & proxies?
What is the typical Spring pattern for solving this type of situation?
So it is now many weeks later (since asking this question), and consequently my knowledge level has been expanding exponentially, so I figured I might as well answer my question for anyone who might find it helpful (not to mention the question wasn't very clear to begin with).
The basic answer is: use proxies. Since a singleton is only instantiate 1 time, you cant inject another class which has a shorter lifespan, eg. session scope. For those requiring more information, checkout stateful vs stateless beans. More or less what I ended up doing is this... the services contain STATELESS code for manipulating data (think verbs; RegisterUserSvc, AddPartSvc, etc). The data which these services manipulate is stateful. For instance, each user has a own copy of their own data object, lets say TodoListBean, which is in a different state for each user.
So how does a service, AddTodoItemService for instance, manipulate this data? This is where the proxy comes into play. When instantiated, the AddTodoItemService gets injected with a proxy for the TodoListBean, instead of the actual object. That way when the service needs to access the TodoListBean the container will serve up the a TodoListBean out of the current users session, and therefore the service will be operating on the correct bean (based on which user invoked the service), instead of doing something silly like having numerous copies of the service included in each users session scope.

Unity performance considerations with container controlled lifetime - Is there any reflection lag with multiple Resolve<T>() calls?

Is there any reflection performance considerations when repeatedly calling container.Resolve<T>() when a resolution has already been established?
I'm using it in an MVC controller to resolve my data service, so it will be called on every HTTP request. I'm storing the container instance in Application state, and I'm using container controlled lifetime so it maintains a singleton instance of my resolved class. My assumption is that while the container is alive and has created a new instance of the service, it will not need to use reflection on subsequent calls to resolve it.
I'm considering keeping a reference to the resolved class instead if performance of Resolve<T>() is an issue. But with the singleton lifetime setup, it seems like I would be duplicating something that's already built-in.
While not directly answering your question, Torkel Ödegaard's IoC container benchmarks suggest that you'll not be seeing a major performance hit related to resolving dependecies.

Resources