简体   繁体   中英

How can share an object between an ASP.Net page and other projects

I have an object (ClientConfiguration) that I use on almost every page on my site, as well as in many methods that exist in related projects that get compiled into the website.

What I am doing now is creating and populating the object on each page load, and storing it in the HttpContext. This works great for anything in the UI project; and for anything in the dll projects, I pass the ClientConfiguration to any methods that may need to use it.

What I would rather do is have a "global" property that is shared among all of the related projects so I don't have to pass it around.

Is there a good way to accomplish this?

在其他库项目中添加System.Web.dll作为引用后,您可以直接在HttpContext中访问该对象,而无需将其作为参数传递。

This depends a bit on where initial configuration is being stored (xml file, database or something else) but you'll see the point.

If these are global configuration settings that are same for all application users you can create a class like this

public class Config
{
    public static ClientConfiguration Current
    {
        get
        {
            if (HttpContext.Current.Application["clientconfig"] == null)
            { 
                //Fill object from database
            }

            return HttpContext.Current.Application["clientconfig"] as ClientConfiguration;
        }

        set
        { 
            //store object in database 

            //invalidate what is stored in application object 
            //so that it will be refreshed next time it's used
            HttpContext.Current.Application["clientconfig"] = null;
        }
    }
}

This will store the ClientConfiguration in global Application object and make it available in all pages so you don't have to create it in page load.

You can just use it like this

private void Foo()
{
    ClientConfiguration config = Config.Current;
}

If you have multiple projects that need to share same data then it's best to store the object in database or in shared XML file and create new class library project so that you can just include reference to the Config class.

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