简体   繁体   English

asp.net中基类中的共享数据

[英]Shared data in base class in asp.net

I have a set of aspx pages which are made of up usercontrols. 我有一组由用户控件组成的aspx页面。 Each usercontrol inherits from a base class. 每个用户控件都从基类继承。 In that base class I want to put some common data objects (via EF) that I need access to in my user controls. 在该基类中,我想将一些需要访问的公用数据对象(通过EF)放入我的用户控件中。 How can I do this efficiently so that each user controls accesses the same class instance or copy of the data? 如何有效地做到这一点,以便每个用户控件都可以访问相同的类实例或数据副本?

You could use the Singleton Per Request pattern . 您可以使用“ 每个请求单例”模式 It's useful if you only want a single instance of a object to be available during the lifetime of a request. 如果您只希望在请求的生存期内仅对象的单个实例可用,则该功能很有用。

It does this by storing the item in the HttpContext.Items collection. 它通过将项目存储在HttpContext.Items集合中来实现。

public class SingletonPerRequest
{
    public static SingletonPerRequest Current
    {
        get
        {
            return (HttpContext.Current.Items["SingletonPerRequest"] ??
                (HttpContext.Current.Items["SingletonPerRequest"] = 
                new SingletonPerRequest())) as SingletonPerRequest;

        }
    }
}

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

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