When is the Session Property in Controller Initialized? - asp.net-mvc

When is the Session property in Controller Initialized?
From what I see it is not initialized when the constructor is called. So when it's initialized?

It looks to me from the source, that the controller context (which contains the HttpContext and thus the Session) is provided to the controller when the action is invoked by the ControllerActionInvoker. It's also available to filters via the filter's context object on the filter's main methods.

So this is old, but I thought I'd leave the answer here for someone in the future.
http://forums.asp.net/t/1500473.aspx
Some guy says the Session is created when you first use it. My own experience bears this out, with one caveat, if you have two action methods executing simultaneously then the first one to access the Session appears to end up with a different Session to the second. I put a lock around my code to try and solve this, but ended up solving it by initialising my Session earlier on in my process.

Related

Declaring DbContext for an MVC controller

Looking at some of the MVC examples online, I've see that typically in a controller the DbContext variable is declared as a private member variable (i.e. global) and accessible to all the methods.
But, I recently came across an article on ASP.NET Identity, and noticed in the controller, the DbContext is declared within each method (that requires it).
Is there a security benefit to this approach? Perhaps limit the lifespan of the security object(s) for better overall security?!?!
If not, then I see the first approach being more efficient, where the database context is instantiated upon the controller loading.
Below is all I could find about DbContext, but nothing to really answer my question.
DbContext declaration - Framework 4.1 - MVC 3.0
MVC, DbContext and Multithreading
On every request, a new instance of the controller is constructed. Therefore, for all intents and purposes, it does not really matter whether the dbcontext is instantiated in the constructor vs encapsulated in any given method.
Aside from a style choice, reasons to declare and contain a dbcontext in a given method is that:
Methods that do not need it will not instantiate the context, eliminating the overhead (if there is any). This can also be accomplished using a lazy initialization pattern.
The context is disposed of immediately as soon as a method is done with it, rather than at the end of the request. Generally this should not be a concern though; usually if users are waiting around for longer than a few seconds you have a bigger problem.
Different methods use different contexts.
Among others, some reasons to declare a single context and instantiate it once:
You have only one place that instantiates a context rather than many. In a typical application, most pages will need some information from the database anyway.
Methods that call other methods will not each hold on to their own instance of a context object.
You can create a base controller class that by default creates a dbcontext object, allowing you to be DRY in all inherited controllers.
Answer from #Ic. is pretty good. I wanted to add that if you need to pass information from your Request into your DbContext constructor then you need to create the instance of your DbContext inside your action methods. The reason is the Request object will be null till the control enters your action method.
More information: I had a need to build connection string dynamically depending on the location of the user. I saved the location as a cookie that I accessed through Request object. I had a valid Request inside the action method but it was null inside the constructor or at the class level properties of the controller.

Why is CDI-Event creating a new instance instead of using existing Oberserver?

I am facing a problem with CDI on JBoss AS 7.1.1
I have two JSF-beas, where one has the CODI ViewAccessScope (Bean A) which shows all entities, and the second is plain RequestScoped (Bean B). Each Bean get a, so called, Presenter injected which takes care of all presentation logic. So far so good.
The Presenter from Bean B is responsible for creating a new entity (calling service...bla...blubb) and when everything is done Bean B is redirecting to another page but since Bean A now has to reload its content I introduced the JEE-6 Observer.
In detail: Both Beans (A & B) get a particular Presenter injected (which has a backrefrence to the jsf-bean via a interface). Bean-B-Presenter fires an event after the entity was successfully created, so that then Bean-A-Presenter (the Observer) can reload the data and notify Bean-A about the changes.
The Problem: I am getting as NullPointerException when the observing Presenter (A) reloads its data because the reference to Bean A is lost. The reason why this happens is because CDI is obviously creating a new Presenter-object (its annotated with #Named) instead of using the one that is coupled with Bean-A.
Workaround: when I use Bean-A as the Observer than everything works.
My code is pretty much the same as seen in the link I added. I don't understand why a new instance is created when firing the event.
UPDATE regarding LightGuards comment:
The presenter beans are just annotated with #Named (which should be Dependent-Scope by default).
I had a look at the Weld-Documentation and it looks like this scope is somehow isolating my beans from each other. I need the presenters to be a new instance, each time a view (jsf-bean) gets initialized (so no Singletons). On the other hand I want to be able to send events between them, meaning that only the already existing instances get notified (not that a new instance is created).
I just did a test with the presenters being RequestScoped. This doesnt work either because now on every HTTP-Request I get a new Presenter even though the view (jsf-bean) to which it belongs is ViewAccessScoped. SessionScope of course works...but this would result in the wrong design.
Sounds like you'll need to create your own scope for this usecase. None of the default scopes sound like they fit your need. Another option would be to look at MyFaces CODI and the conversation scope they're written.
Please ensure that your observers aren't private.
And you have to ensure that you redirect correctly.

Is an instance of my controller constructor created every time I request a new page in MVC3

I have quite a few things in the constructor of my controller. Is it the case that every time I request a new page with MVC3 then the constructor executes?
A controller instance is required to serve each request. And to obtain this instance (obviously) the controller constructor is called on each request. This being said you should avoid doing many things in this constructor. There are cases for example where for some particular action on this controller you don't need all this initialization and despite this if you put it in the constructor, it will be executed. If the tasks you perform are simply instantiating some other dependencies that your controller needs, then you shouldn't worry about performance, you should worry about properly architecting your application as this job should be handled by a DI framework.
Another common gotcha is that inside the constructor you don't yet have access to the HttpContext and some properties such as Request, Response, ... might not be available in the controller constructor. They become available in the Initialize method.
All this to say that I recommend you avoid putting code (other than storing ctor argument dependencies into private variables for injecting things like services, repositories, ...) in your constructor.
The Controller base class includes the ControllerContext which is a per-request context for a controller which includes references to HttpContext for example.
Let that sink in a moment.
It's very easy to write a custom ControllerBuilder or use the new DependencyResolver to serve up a singleton controller using your favorite DI container. But what that means is your controller may hold onto state from a previous request.
In fact, one of the most common bugs when people use Castle Windsor (which uses Singleton by default I've been told) to create their controllers is they get weird behavior.
As others have pointed out, if your controller is doing a lot of work in the constructor, refactor that work into a dependency on your controller which gets passed in via your controller's contstructor. Let's call that dependency a "service".
That service can itself be a singleton (as long as it doesn't hold onto per-request state) and you can use the DependencyResolver combined with your DI container to instantiate your controllers.
It's up to the ControllerFactory to determine this; the controller factory serves up the controller instance. You could build in the ability to cache the controller, but: it would be better not to pass those references via the ctor of the controller. It would be better to cache each reference separately, and pass to the controller during construction, and let the controller get recreated everytime. If you cache the controller, it will cache other references potentially like HttpContext, which would be not the current request.
HTH.
Yes, M Jacob and this helps us making Data Access request for new DataContext in each request and it is very efficient. it is recommended to initialize a new DataContext (in your controller constructor) in each request rather than making persistent DataContext.
Internet is stateless and the server cannot really distinguish you from any other person out there (technically speaking, ignoring sessions and cookies). You are served the content and connection with you is ended. On your new request the things start from scratch. I agree with you that inability to keep an object alive is an overhead, but even bigger overhead would be if million users made a request with a different requests to the same object. Keeping million copies of the same object is next to impossible.
Regards,
Huske

Why are Controller Constructors fired before the Initialize method

I have a base Controller ApplicationController that needs to grab the URL Host and do some processing before the child controllers are fired. Since controller constructors are fired before RequestContext is initialized I have to override Initialize method to do my processing.
ApplicationController:
Protected Overrides Sub Initialize(ByVal requestContext As System.Web.Routing.RequestContext)
MyBase.Initialize(requestContext)
Dim host as String
host = Request.Url.Host.ToString
End Sub
What is the logic behind having Controller Constructors fire before the Initialize method?
Also what are the rules to what should be placed in the Initialize Method.
Assuming that constructors are the first instance method ever to be fired in a .NET class, that shouldn't come as a surprise and is not really something MVC specific. It's more how the .NET framework works.
The MVC framework needs to first instantiate a controller and then initialize it => it calls the constructor first. And because performing lots of code that could potentially might throw exceptions, etc... is not always best to be put in a constructor => the presence of the Initialize method. As far as this method is concerned I must admit that I have written lots of ASP.NET MVC code and never had to use it. Action filters always seemed like a better alternative.
So to answer your question:
Also what are the rules to what should be placed in the Initialize Method.
I've never ever put any code and never ever need to override this method. I've always preferred using action filters because this way I am no longer in the obligation of deriving from a common base controller (not that this is a problem).
Sometimes, maybe you would want your request to initialize your variables, so in this case you should use the Initialize method.
For example, if you want to initialize some variables in a different way when the request is local or not, etc.

Accessing user session from a custom routing class

Is there some way to acces the user object from a custom routing class?
I'd like to add a parameter when generating a url, and that parameter is inside the user session, so I need to access it.
The only way I found to access is using the sfContext::getInstance()->getUser(), but it's known to be inefficient.
Thanks!
I'd write it the way you mention - I've used that method in similar situations and never had an issue performance wise, and suspect you will be the same.
Also, never heard this mentioned as inefficient, but it is a little bit frowned upon because it couples the route to the context. An alternative that would overcome this would be to pass the variable to the route as you would any other parameter (or the user object if you need the whole thing). If you need to do this a lot, you can always make a custom url helper that wraps the existing url_for method, adding this param to any other details passed.
A workaround I have implemented (for now), is getting some data from somewhere (not ideal, I'm willing to access the user session yet), and set a new parameter inside $params, in the generate method of the custom routing class.
Hope it helps...

Resources