最近發佈了關於如何不安全的靜態變量的問題,自從我發現我需要擺脫它們。但我無法弄清楚如何?正在爲每個類想一個靜態的Get()方法,該方法返回一個單獨的實例,但是那個實例必須被聲明爲靜態的。ASP.NET MVC如何避免靜態變量?
所以唯一的方法就是讓實例引用(對於每個助手,I.E用戶helper.cs,imagehelper.cs等)是將它們聲明爲某種全局可訪問類的實例屬性?但是,哪一類?有什麼我在這裏失蹤?以下示例類的
代碼,我需要改變:
sing System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Mvc.Mailer;
namespace MVCWebsite.Helpers
{
public class AppSettings
{
public static void OnAppInit()
{
//General
AppName = "MyApp";
DesktopBaseURLs = new Dictionary<string, string>();
DesktopBaseURLs.Add("dev", "localhost:50560");
DesktopBaseURLs.Add("test", "www.test.whatever.com");
DesktopBaseURLs.Add("live", "www.whatever.com");
MobileBaseURLs = new Dictionary<string, string>();
MobileBaseURLs.Add("dev", "m.local.whatever.com");
MobileBaseURLs.Add("test", "m.test.whatever.com");
MobileBaseURLs.Add("live", "m.whatever.com");
//Emails
EmailHostName = AppName + ".com"; //For the moment atleast
NoReplyEmailAddress = "[email protected]" + EmailHostName.ToLower();
SupportEmailAddress = "[email protected]" + EmailHostName.ToLower();
ErrorEmailAddress = "[email protected]" + EmailHostName.ToLower();
//Resources
TempFileURL = "/content/temp/";
UserDataURL = "/content/user-content/";
ProfilePicturesURL = UserDataURL + "profile-pictures/";
var a = GlobalHelper.GetURLAsServerPath(ProfilePicturesURL);
var b = a;
}
//General
public static string AppName { get; set; }
public static Dictionary<string, string> DesktopBaseURLs;
public static Dictionary<string, string> MobileBaseURLs;
//Emails
public static string EmailHostName { get; set; }
public static string NoReplyEmailAddress { get; set; }
public static string SupportEmailAddress { get; set; }
public static string ErrorEmailAddress { get; set; }
//Resources
public static string UserDataURL { get; set; }
public static string TempFileURL { get; set; }
public static string ProfilePicturesURL { get; set; }
//Methods
public static void SetAppURL()
{
}
}
}
任何你沒有將這些存儲在web.config中的理由? –
你爲什麼認爲你需要靜態變量? –
考慮使用IoC框架。 – SLaks