I have a Singleton Class, It will Initial in every request, But I just want it Initial only 1 time in hole application life. which mean only first request need Initial it.:
public class TestUtilitys
{
#region Instance
private TestUtilitys(){
// Execute in every request
Log.Debug("Initial");
}
private static TestUtilitys_instance;
public static TestUtilitys Instance
{
get
{
if (_instance == null)
_instance = new TestUtilitys();
return _instance;
}
}
#endregion Instance
private string Pro;
}
And then I can access it in every request when Action get it in Controller.
public class TestAction(){
if (null == TestUtilitys.Instance.Pro)
{
// execute in every request
TestUtilitys.Instance.Pro = "test";
}
}
In my Web.config, I just add these different with my another project
<!-- cache -->
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<clear />
<!-- 8 Hour -->
<add varyByCustom="NavStatic" varyByParam="*" duration="28800" name="NavStatic" location="Server" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<compilation targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
<sessionState mode="InProc" timeout="43200" />
As you see, the 2 position will execute every time when the Action get a request. I don't know Why The Singlton always need to ReInitial in every request. I'm not clear any cache or something. I just use DevTrends.MvcDonutCaching for my project. I'm using IIS8.5 on Windows Server 2012 R2. the .Net version is : 4.5.1 But on my Local machine it's all fine on my WIN8.1(use Visual Studio 2013) when I debug.
Update
In the Singleton class method, I also find after I set the memory cache in last request, next request can't get it from memory cache. it will be null,
// In a method for set Cache
// set in last request
MemoryCache.Default.Set("key", obj, DateTime.Now);
`` ``
// In an another method for get Cache
// get it in next request, but obj will be null
object obj = MemoryCache.Default.Get("key");
What's wrong my website. How do I fixed it?
Update 2
I search a lot, I saw some people said: Static fields are shared across the whole AppDomain. But what's going on with my website??
Answer: Static property always null in every request after set value on ASP.NET MVC5