简体   繁体   English

如何在asp.net页面中启动页面时初始化对象

[英]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. 现在我想在页面内使用ctxt并控制事件。 I tried to initialize it in page load but i cant access ctxt. 我尝试在页面加载中初始化它但我无法访问ctxt。

In general you'd need to declare a field which you'd instantiate in the constructor or page_load/page_init. 通常,您需要声明一个您在构造函数或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. 如果您需要更强大的功能,或者需要实例存在,您可以从其他无法或不想明确传递的对象中使用它,您可以使用IoC容器等作为Castles Windsor,您可以使用它来解析和实例化PerWebRequest资源 - 但它可能需要一些设置并且有自己的怪癖。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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