简体   繁体   中英

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.

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.

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM