2010-06-22 2 views
2

내 코드에서 특정 값을 저장하기 위해 정적 필드를 사용하고 있습니다.정적 변수의 대안?

public static int webServiceId; 

나는 그것을 제거하고 다른 해결책을 사용합니다. 하지만 값은 포스트 백 후에 유지되어야합니다. 여기에서는 Session 또는 ViewState를 사용할 수 없습니다. 내가 서비스 (서비스 계층)에서 작업하고 있습니다.

예 :

내가 xyz.cs 파일의 아래 방법에서 웹 서비스 ID를 얻을 :

public int SetWebServiceInformation(int? webServiceID, string webServiceName) 
{ 
    context.WebService_InsertUpdate(ref webServiceID, webServiceName); 
     webServiceId = webServiceID.Value; 
     return webServiceID.Value; 

} 

을 다음 다른 클래스 파일의 다른 방법 (예를 들어 abd.cs 파일)로 이동 제어합니다. 메서드 예외를 호출 할 때 첫 번째 클래스 파일 (xyz.cs)의 메서드 LogError (예외 오류)가 호출됩니다. 그리고 컨트롤이 우리 클래스 파일 (xyz.cs)에 돌아 왔을 때 webservice Id가 필요합니다. 우리는 webservice Id에 따라 예외 정보를 데이터베이스에 저장하는 데 사용하고 있습니다.

protected void LogError(Exception error) 
{ 
    ----//some logic to get errorLogID//--- 

    if (errorLogID > 0) 
      WebServiceErrorLogging(errorLogID, webServiceId); 
    //here we have webServiceId is a static variable 
} 
+0

정적 변수를 사용할 수 없다는 의미의 제한이 무엇입니까? –

+2

@David : ASP.NET/WCF –

+0

@Henk에서 정적 병을 사용하면 안됩니다. ASP.NET/WCF –

답변

0

당신은 Singleton 클래스의 webServiceId을 포장 할 수있다.

public sealed class WebServiceSettings 
{ 
    private static readonly WebServiceSettings instance=new WebServiceSettings(); 
    private static int webServiceId; 

    static WebServiceSettings() 
    { 
     webServiceId = //set webServiceId 
    } 

    private WebServiceSettings(){} 

    public static WebServiceSettings Current 
    { 
     get 
     { 
      return instance; 
     } 
    } 

    public int WebServiceId {get{return webServiceId;}} 
} 

그런 다음 아이디를 호출 할 수

WebServiceSettings.Current.WebServiceId; 

이 클래스는, 본질적으로는 한 번만 구성되도록합니다 (C#으로, 정적 생성자는 한 번 호출 할 수익을 창출하고 있습니다). 따라서 WebServiceId을 채울 생성자의 코드는 한 번만 실행됩니다.

+0

David 에서뿐만 아니라이 사실을 설명 할 수 있습니까? 사실 당신이 여기서 설명하려고하는 것을 얻지 못했습니다. 여기에 코드를 작성할 수 있다면 정말 도움이됩니다. –

+0

David, 정적 var 밑에 Singleton을 표시 할 수있는 경우에만이 기능이 유용합니다. –

+0

이 컨텍스트에서 싱글 톤을 사용할 때의 문제점은 무엇입니까? 확실히 ID는 한 번만 만들어야합니다. –

1

Singleton 구현을 고려 했습니까?

그런 식으로 매개 변수를 저장하기위한 "전역"클래스를 가질 수 있습니다.

using System.Runtime.CompilerServices; 

public class Singleton 
{ 
    private static Singleton Instance = null; 
    static readonly object padlock = new object(); 


    // The private constructor doesnt allos a default public constructor 
    private Singleton() {} 

    // Synchronized "constructor" to make it thread-safe 
    [MethodImpl(MethodImplOptions.Synchronized)] 
    private static void CreateInstance() 
    { 
     lock(padlock) 
     { 
      if (Instance == null) 
      { 
        Instance = new Singleton(); 
      } 
     } 
    } 

    public static Singleton GetInstance() 
    { 
     if (Instance == null) CreateInstance(); 
     return Instance; 
    } 

    public int webServiceId {get; set;} 


} 

// Test class 
public class Prueba 
{ 
    private static void Main(string[] args) 
    { 
    //Singleton s0 = new Singleton(); //Error 
    Singleton s1 = Singleton.GetInstance(); 
    Singleton s2 = Singleton.GetInstance(); 
    if(s1==s2) 
    { 
     // Misma instancia 
    } 
    } 
} 

코드는 상기 (하는 GetInstance() 메소드를 통해 정적)가 인스턴스화 될 때, 클래스의 고유 인스턴스를 반환하는 클래스를 구현한다.

+0

이미 제안되었습니다. –

+0

@David Neale - 다른 사람들은 당신과 같은 대답을 제안 할 자유가 있습니다. 그것을 금지하는 법안은 없습니다. – Oded

+0

게시하는 동안 쓰고있었습니다 :) 삭제해야합니까? –

관련 문제