![](/img/trans.png)
[英]Static property of inner static class of non-static class shared between instances of the non-static class?
[英]Static class with non-static members shared across instances of ASP.NET MVC app?
我有幾個項目的解決方案,包括ASP.NET MVC項目和WPF應用程序。 在數據庫中,我有一些常規設置要在兩個應用程序中使用。 為此,我創建了一個類庫Foo
,該類庫將設置加載到字典中,並提供Get(string key)
方法以從字典中訪問特定設置。 由於設置可以被用戶覆蓋,因此我添加了一個包含UserId的屬性。 Get()
方法自動負責檢查和使用UserId
屬性。 這樣,我不需要每次調用Get()
方法時都將UserId作為參數傳遞。
對於WPF應用程序,這工作得很好,因為只有一個實例正在運行。 但是對於Web項目,我只希望字典填充一次(在Application_Start()
),並且所有訪問該站點的用戶都可以使用該字典。 如果我將類實例設為靜態,則效果很好。 但是,這不允許我擁有不同的UserIds
,因為訪問該網站的每個用戶的每個用戶都將被覆蓋。 解決此問題的最佳方法是什么?
這是我到目前為止嘗試過的(非常簡化):
類庫:
public class Foo ()
{
private Dictionary<string, string> Res;
private int UserId;
public Foo ()
{
Res = DoSomeMagicAndGetMyDbValues();
}
public void SetUser (int userId)
{
UserId = userId;
}
public string Get(string key)
{
var res = Res[key];
// do some magic stuff with the UserId
return res;
}
}
Global.asax:
public static Foo MyFoo;
protected void Application_Start()
{
MyFoo = new Foo();
}
UserController.cs:
public ActionResult Login(int userId)
{
MvcApplication.MyFoo.SetUser(userId); // <-- this sets the same UserId for all instances
}
如何將設置存儲在Dictionary<int<Dictionary<string, string>>
,其中外層詞典的Key
是UserId
,而鍵0
保存為默認設置? 當然,這意味着您必須將用戶ID傳遞給Get和Set方法。
然后,您可以執行以下操作:
public static class Foo
{
private static Dictionary<int, Dictionary<string, string>> settings;
/// <summary>
/// Populates settings[0] with the default settings for the application
/// </summary>
public static void LoadDefaultSettings()
{
if (!settings.ContainsKey(0))
{
settings.Add(0, new Dictionary<string, string>());
}
// Some magic that loads the default settings into settings[0]
settings[0] = GetDefaultSettings();
}
/// <summary>
/// Adds a user-defined key or overrides a default key value with a User-specified value
/// </summary>
/// <param name="key">The key to add or override</param>
/// <param name="value">The key's value</param>
public static void Set(string key, string value, int userId)
{
if (!settings.ContainsKey(userId))
{
settings.Add(userId, new Dictionary<string, string>());
}
settings[userId][key] = value;
}
/// <summary>
/// Gets the User-defined value for the specified key if it exists,
/// otherwise the default value is returned.
/// </summary>
/// <param name="key">The key to search for</param>
/// <returns>The value of specified key, or empty string if it doens't exist</returns>
public static string Get(string key, int userId)
{
if (settings.ContainsKey(userId) && settings[userId].ContainsKey(key))
{
return settings[userId][key];
}
return settings[0].ContainsKey(key) ? settings[0][key] : string.Empty;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.