从数据库获取 AppSettings缓存

发布于 2024-10-15 01:23:01 字数 4295 浏览 3 评论 0原文

在我的办公室,我们认为我们要将 Web.Config 的 AppSettings 放入数据库中。因此,我创建了以下内容,但对代码的几个方面有一些疑问。

所以我的问题是:
UTILITY 类中包含“Cache cache = new Cache()”的行可能是错误的,因为它创建了一个新的缓存对象。

问:那么,我应该为这条线做什么?

...任何帮助表示赞赏。

总体目标是能够进行如下调用:

Utility.GetConfigurationValue(ConfigurationSection.AppSettings, "myVariable");

...并自动从缓存或数据库中检索。

实用程序代码:

public static class Utility
{
    #region "Configurations"

    public static String GetConfigurationValue(ConfigurationSection section, String key)
    {
        Configurations config = new Configurations();
        Cache cache = new Cache(); // <--- This is probably wrong!!!!

        if (!cache.TryGetItemFromCache<Configurations>(out config))
        {
            config.List(SNCLavalin.US.Common.Enumerations.ConfigurationSection.AppSettings);
            cache.AddToCache<Configurations>(config, DateTime.Now.AddMinutes(15));
        }

        var result = (from record in config
                      where record.Key == key
                      select record).FirstOrDefault();

        return (result == null) ? null : result.Value;
    }

    #endregion
}

扩展代码:

public static class Extensions
{
    #region "System.Web.Caching"

    public static void Remove<T>(this Cache cache) where T : class
    {
        cache.Remove(typeof(T).Name);
    }
    public static void AddToCache<T>(this Cache cache, object item, DateTime absoluteExpiration) where T : class
    {
        T outItem = null;
        if (cache.TryGetItemFromCache<T>(out outItem))
            return;

        cache.Insert(typeof(T).Name,
                item,
                null,
                absoluteExpiration,
                System.Web.Caching.Cache.NoSlidingExpiration,
                System.Web.Caching.CacheItemPriority.Normal,
                null);
    }
    public static bool TryGetItemFromCache<T>(this Cache cache, out T item) where T : class
    {
        item = cache.Get(typeof(T).Name) as T;
        return item != null;
    }

    #endregion
}

列表类别代码:

public class Configurations : List<Configuration>
{
    #region CONSTRUCTORS

    public Configurations() : base()
    {
        initialize();
    }
    public Configurations(int capacity) : base(capacity)
    {
        initialize();
    }
    public Configurations(IEnumerable<Configuration> collection) : base(collection)
    {
        initialize();
    }

    #endregion

    #region PROPERTIES & FIELDS

    private Crud _crud;

    #endregion

    #region EVENTS
    #endregion

    #region METHODS

    private void initialize()
    {
        _crud = new Crud("CurrentDbConnection");
    }

    public Configurations List(ConfigurationSection section)
    {
        using (DbCommand dbCommand = _crud.Db.GetStoredProcCommand("spa_LIST_SecConfiguration"))
        {
            _crud.Db.AddInParameter(dbCommand, "@Section", DbType.String, section.ToString());

            _crud.List(dbCommand, PopulateFrom);
        }

        return this;
    }

    public void PopulateFrom(DataTable table)
    {
        this.Clear();

        foreach (DataRow row in table.Rows)
        {
            Configuration instance = new Configuration();
            instance.PopulateFrom(row);
            this.Add(instance);
        }
    }

    #endregion
}

项目类别代码: >

公共类配置 { #地区建设者

public Configuration()
{
    initialize();
}

#endregion

#region PROPERTIES & FIELDS

private Crud _crud;

public string Section { get; set; }
public string Key { get; set; }
public string Value { get; set; }

#endregion

#region EVENTS
#endregion

#region METHODS

private void initialize()
{
    _crud = new Crud("CurrentDbConnection");
    Clear();
}

public void Clear()
{
    this.Section = "";
    this.Key = "";
    this.Value = "";
}
public void PopulateFrom(DataRow row)
{
    Clear();

    this.Section = row["Section"].ToString();
    this.Key = row["Key"].ToString();
    this.Value = row["Value"].ToString();
}

#endregion

}

At my office, it has been deemed that we are to put our AppSettings for the Web.Config in the database. As such, I created the following, but have some doubts about a couple aspects of the code.

So my question is:
The line containing "Cache cache = new Cache()" in the UTILITY class is probably wrong because it creates a NEW cache object.

Q: So, what should I be doing for that line?

...any help is appreciated.

The overall objective was to be able to make a call like this:

Utility.GetConfigurationValue(ConfigurationSection.AppSettings, "myVariable");

...and have it retrieve from the cache or the database auto-magically.

THE UTILITY CODE:

public static class Utility
{
    #region "Configurations"

    public static String GetConfigurationValue(ConfigurationSection section, String key)
    {
        Configurations config = new Configurations();
        Cache cache = new Cache(); // <--- This is probably wrong!!!!

        if (!cache.TryGetItemFromCache<Configurations>(out config))
        {
            config.List(SNCLavalin.US.Common.Enumerations.ConfigurationSection.AppSettings);
            cache.AddToCache<Configurations>(config, DateTime.Now.AddMinutes(15));
        }

        var result = (from record in config
                      where record.Key == key
                      select record).FirstOrDefault();

        return (result == null) ? null : result.Value;
    }

    #endregion
}

THE EXTENSION CODE:

public static class Extensions
{
    #region "System.Web.Caching"

    public static void Remove<T>(this Cache cache) where T : class
    {
        cache.Remove(typeof(T).Name);
    }
    public static void AddToCache<T>(this Cache cache, object item, DateTime absoluteExpiration) where T : class
    {
        T outItem = null;
        if (cache.TryGetItemFromCache<T>(out outItem))
            return;

        cache.Insert(typeof(T).Name,
                item,
                null,
                absoluteExpiration,
                System.Web.Caching.Cache.NoSlidingExpiration,
                System.Web.Caching.CacheItemPriority.Normal,
                null);
    }
    public static bool TryGetItemFromCache<T>(this Cache cache, out T item) where T : class
    {
        item = cache.Get(typeof(T).Name) as T;
        return item != null;
    }

    #endregion
}

THE LIST-CLASS CODE:

public class Configurations : List<Configuration>
{
    #region CONSTRUCTORS

    public Configurations() : base()
    {
        initialize();
    }
    public Configurations(int capacity) : base(capacity)
    {
        initialize();
    }
    public Configurations(IEnumerable<Configuration> collection) : base(collection)
    {
        initialize();
    }

    #endregion

    #region PROPERTIES & FIELDS

    private Crud _crud;

    #endregion

    #region EVENTS
    #endregion

    #region METHODS

    private void initialize()
    {
        _crud = new Crud("CurrentDbConnection");
    }

    public Configurations List(ConfigurationSection section)
    {
        using (DbCommand dbCommand = _crud.Db.GetStoredProcCommand("spa_LIST_SecConfiguration"))
        {
            _crud.Db.AddInParameter(dbCommand, "@Section", DbType.String, section.ToString());

            _crud.List(dbCommand, PopulateFrom);
        }

        return this;
    }

    public void PopulateFrom(DataTable table)
    {
        this.Clear();

        foreach (DataRow row in table.Rows)
        {
            Configuration instance = new Configuration();
            instance.PopulateFrom(row);
            this.Add(instance);
        }
    }

    #endregion
}

THE ITEM-CLASS CODE:

public class Configuration
{
#region CONSTRUCTORS

public Configuration()
{
    initialize();
}

#endregion

#region PROPERTIES & FIELDS

private Crud _crud;

public string Section { get; set; }
public string Key { get; set; }
public string Value { get; set; }

#endregion

#region EVENTS
#endregion

#region METHODS

private void initialize()
{
    _crud = new Crud("CurrentDbConnection");
    Clear();
}

public void Clear()
{
    this.Section = "";
    this.Key = "";
    this.Value = "";
}
public void PopulateFrom(DataRow row)
{
    Clear();

    this.Section = row["Section"].ToString();
    this.Key = row["Key"].ToString();
    this.Value = row["Value"].ToString();
}

#endregion

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

稀香 2024-10-22 01:23:01

您已经正确识别了问题 - 当前代码在每次调用 GetConfigurationValue 时都会创建一个新的 Cache 实例,这违背了缓存的目的。您需要将 Cache 实例设为静态,而不是每次都创建一个新实例。

public static class Utility
{
    private static Cache cache = new Cache();  // Static class variable

    #region "Configurations"

    public static String GetConfigurationValue(ConfigurationSection section, String key)
    {
        Configurations config = new Configurations();
        // Cache cache = new Cache(); --- removed

        ...
    }
}

You have correctly identified the problem - the current code creates a new Cache instance on each call to GetConfigurationValue which defeats the purpose of caching. You need to make the Cache instance static rather than creating a new instance each time.

public static class Utility
{
    private static Cache cache = new Cache();  // Static class variable

    #region "Configurations"

    public static String GetConfigurationValue(ConfigurationSection section, String key)
    {
        Configurations config = new Configurations();
        // Cache cache = new Cache(); --- removed

        ...
    }
}
回忆凄美了谁 2024-10-22 01:23:01

答案附录:
我确实(事实上)需要将缓存变量指向其他东西。直到我在实用程序类中执行以下操作后它才会起作用。

private static Cache cache = System.Web.HttpRuntime.Cache;

ADDENDUM TO ANSWER:
I did (in fact) need to point the cache variable to something else. It wouldn't work until I did the following in the Utility class.

private static Cache cache = System.Web.HttpRuntime.Cache;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文