how to initialize an object at start up of a page in a asp.net page
I need to initialize an object from the start up of an page and use the objects through out the particular page how can i do it.
//Block to be initialized
XTContext.UserContext UContext = new XTContext.UserContext();
XTContext.Context ctxt = new XTContext.Context();
XTErrorCollection.ErrorCollection eContext = new XTErrorCollection.ErrorCollection();
ctxt = (XTContext.Context)Cache["sessionfContext"];
ctxt.eContext = eContext;
ctxt.uContext = UContext开发者_如何学编程;
now i want to use the ctxt inside the page and control events. I tried to initialize it in page load but i cant access ctxt.
Try this instead -
public partial class YourPage : System.Web.UI.Page
{
XTContext.UserContext UContext;
XTContext.Context ctxt;
XTErrorCollection.ErrorCollection eContext;
protected void Page_Load(object sender, EventArgs e)
{
UContext = new XTContext.UserContext();
ctxt = new XTContext.Context();
eContext = new XTErrorCollection.ErrorCollection();
ctxt = (XTContext.Context)Cache["sessionfContext"];
ctxt.eContext = eContext;
ctxt.uContext = UContext;
}
}
In general you'd need to declare a field which you'd instantiate in the constructor or page_load/page_init. Depending on what it is you're creating you may also want to explicitly dispose of the resources at the end as well.
public class MyPage
{
private object myobject = null;
public MyPage()
{
myobject = new Object();
}
}
You can then pass through to other classes as appropriate. If you need something more powerful for this or need the instance to exist in a way which you can make use of it from other objects where you can't or don't want to pass through explicitly you could make use of an IoC container such as Castles Windsor which you can use to resolve and instantiate resources PerWebRequest - but it can take a little set up and has its own quirks.
精彩评论