I am new to WebForms, I think I have a rather simple question. I often see people initialize any kind of dependencies in the page_load-method of their page class. Is that a common thing to do ?
Things I would usually write in the constructor.
How do I decide what belongs in the constructor and what is better placed in the page_load handling method
You must take a look at asp.net life cycle.
On costructor method you can write lot of code, declaring variables and using classes and libraries.
But if you need some asp.net elements (Page
, Controls
, Session
, QueryString
etc) you need to be in Page_Load
or in other methods of life cycle.
When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. It is important for you to understand the page life cycle so that you can write code at the appropriate life-cycle stage for the effect you intend. Additionally, if you develop custom controls, you must be familiar with the page life cycle in order to correctly initialize controls, populate control properties with view-state data, and run any control behavior code. (The life cycle of a control is based on the page life cycle, but the page raises more events for a control than are available for an ASP.NET page alone.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With