2017-04-19 66 views
0

我们将所有应用程序会话存储到Global类中。如何正确地将应用程序会话存储到静态实例中?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.SessionState; 
namespace MyApp 
{ 
    [Serializable] 
    public class AppSession : IRequiresSessionState 
    { 
     //Name that will be used as key for Session object 
     private const string SESSION_SINGLETON = "MyappSession"; 

     string _UserName; 
     int? _UserID ,_ClientID; 
     public int? UserID 
     { 
      get 
      { 
       return _UserID; 
      } 
      set 
      { 
       _UserID = value; 
      } 
     } 
     public string UserName 
     { 
      get 
      { 
       return _UserName; 
      } 
      set 
      { 
       _UserName = value; 
      } 
     } 
     public int? ClientID 
     {  
      get 
      { 
       return _ClientID; 
      } 
      set 
      { 
       _ClientID = value; 
      } 
     } 
     public MarketingSession Marketing { get; set; }  
    } 
} 

我们已经创建了另一个类属性来维护网页会话到不同MarketingSession类,如下

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.SessionState; 

namespace MyApp 
{ 
    [Serializable] 
    public class MarketingSession : IRequiresSessionState 
    { 
     private int? _ChannelId;  
     public int? ChallelId { get 
     { 
      return _ChannelId; } 
      set { _ChannelId = value; } 
     }  
    } 
} 

我不是100%肯定这是它维持会话类或不正确的方法。 和可以在此会话中创建非静态的另一个Class对象吗?

当我添加MarketingSession Class属性时出现以下错误。

错误10的对象引用需要非静态字段, 方法或属性MyApp.AppSession.Marketing.get

更新我,如果我做来管理我的应用程序会话或不正确的方式? 如果方法是正确的,那么如何解决这个错误?

+0

显示在您初始化MarketingSession对象的代码。 –

+0

不在AppSession类中初始化。我会改正方式吗?我应该在AppSession类的MarketingSession属性中使用静态成员吗​​? –

+0

MyApp.AppSession.Marketing.get - 您正在使用此方法,就好像它是静态的。你需要在访问它的属性之前初始化你的AppSession对象,或者首先声明它们是静态的。 –

回答

0

Singleton Pattern似乎是你的情况下最好的解决方案。 您只想初始化Marketing对象一次,并在所有AppSession类实例中共享其值。

这正是这种模式的用途。 请务必阅读以下关于如何使用它并使其适合您目标的最佳方式的示例。

https://msdn.microsoft.com/en-us/library/ff650316.aspx

http://csharpindepth.com/Articles/General/Singleton.aspx

https://www.dotnetperls.com/singleton

+0

好的谢谢..我会按照模式进行初始化。我们已经使用该模式.. –

+0

很高兴我帮助。如果确实是你要找的东西,请务必回答你的问题。 –

+0

我应该在AppSession类中创建其他Marketing类或Normal对象的静态对象吗? 见下文.. static readonly MarketingSession _ms = new MarketingSession(); public MarketingSession Marketing { 得到 { return _ms; } } 还是我有? public MarketingSession Marketing {...} ? –

相关问题