2009-07-11 5 views
1

많은 설정 (이름 - 값 쌍)에 의존하는 ASP.NET MVC 응용 프로그램이 있으므로이 정보를 저장할 계획입니다. SiteSettings라는 데이터베이스 테이블에서. NHibernate를 사용하여 이러한 설정을 얻을 수있는 쉬운 방법이 있습니까? 그리고 웹 응용 프로그램의 설정을 저장할 때 가장 좋은 방법은 무엇입니까? 설정이란 웹 애플리케이션의 프로세스 흐름을 제어하고 비즈니스 규칙에 의해 관리되는 설정을 의미합니다. 이들은 일반적인 연결 문자열 종류의 설정이 아닙니다. 이 주제에 관해 웹에서 많은 정보를 얻을 수 없었습니다. 어쩌면 나는 적당한 키워드에 찾는 것이 아니다, 어떤 도움든지 중대하게 평가 될 것이다.NHibernate를 사용하여 데이터베이스 테이블에 저장된 asp.net mvc 응용 프로그램의 웹 사이트 설정에 액세스

답변

0

제임스가 제안한 해결책과 아주 흡사 한 해결책을 찾았습니다. 전체 사이트에 대한 설정을 관리하는 SiteSettingsService 클래스가 있는데이 사이트는 이라는 인터페이스에 대한 단순 종속성을 가지며 ISiteServiceRepository입니다. 이것은 가장 우아한 해결책은 아닐지 모르지만 그것은 완벽하게 작동합니다. 또한 StructureSet을 사용하여 싱글 톤으로 SiteSettingsService 클래스를 구성했습니다. 따라서, 설정이 필요할 때마다 불필요한 인스턴스 생성을 절약 할 수 있습니다.

//ISiteServiceRepository, an implementation of this uses NHibernate to do just two things 
//i)Get all the settings, ii)Persist all the settings 
using System.Collections.Generic; 
using Cosmicvent.Mcwa.Core.Domain.Model; 

namespace Cosmicvent.Mcwa.Core.Domain { 
    public interface ISiteServiceRepository { 
     IList<Setting> GetSettings(); 
     void PersistSettings(IDictionary<string, string> settings); 
    } 
} 

//The main SiteSettingsService class depends on the ISiteServiceRepository 
using System; 
using System.Collections.Generic; 
using Cosmicvent.Mcwa.Core.Domain; 
using Cosmicvent.Mcwa.Core.Domain.Model; 

namespace Cosmicvent.Mcwa.Core.Services { 
    public class SiteSettingsService : ISiteSettingsService { 

     private readonly ISiteServiceRepository _siteServiceRepository; 
     private IDictionary<string, string> _settings; 

     public SiteSettingsService(ISiteServiceRepository siteServiceRepository) { 
      _siteServiceRepository = siteServiceRepository; 
      //Fill up the settings 
      HydrateSettings(); 
     } 


     public int ActiveDegreeId { 
      get { 
       return int.Parse(GetValue("Active_Degree_Id")); 
      } 
     } 

     public string SiteTitle { 
      get { return GetValue("Site_Title"); } 
     } 

     public decimal CounsellingFee { 
      get { return decimal.Parse(GetValue("Counselling_Fee")); } 
     } 

     public decimal TuitionFee { 
      get { return decimal.Parse(GetValue("Tuition_Fee")); } 
     } 

     public decimal RegistrationFee { 
      get { return decimal.Parse(GetValue("Registration_Fee")); } 
     } 

     public void UpdateSetting(string setting, string value) { 
      if (!string.IsNullOrEmpty(setting) && !string.IsNullOrEmpty(value)) { 
       SetValue(setting, value); 
       PersistSettings(); 
      } 
     } 

     //Helper methods 
     private void HydrateSettings() { 
      _settings = new Dictionary<string, string>(); 
      IList<Setting> siteRepoSettings = _siteServiceRepository.GetSettings(); 
      if (siteRepoSettings == null) { 
       throw new ArgumentException("Site Settings Repository returned a null dictionary"); 
      } 
      foreach (Setting setting in siteRepoSettings) { 
       _settings.Add(setting.Name.ToUpper(), setting.Value); 
      } 
     } 

     private string GetValue(string key) { 
      key = key.ToUpper(); 
      if (_settings == null) { 
       throw new NullReferenceException("The Site Settings object is Null"); 
      } 
      if (!_settings.ContainsKey(key)) { 
       throw new KeyNotFoundException(string.Format("The site setting {0} was not found", key)); 
      } 
      return _settings[key]; 
     } 

     private void SetValue(string key, string value) { 
      key = key.ToUpper(); 
      if (_settings == null) { 
       throw new NullReferenceException("The Site Settings object is Null"); 
      } 
      if (!_settings.ContainsKey(key)) { 
       throw new KeyNotFoundException(string.Format("The site setting {0} was not found", key)); 
      } 

      _settings[key] = value; 
     } 

     private void PersistSettings() { 
      _siteServiceRepository.PersistSettings(_settings); 
     } 

    } 
} 

희망 개발자는 비슷한 문제에 직면 할 수 있기를 바랍니다. 이를 개선하기위한 제안은 환영 할만한 것이 아닙니다.

1

나는 (내가 사용하지 않고있는) nhibernate 또는 모범 사례 (나는 최근에 이것을 내놓았다)의 맥락에서 대답 할 수 없다. 그러나, 그것은 나를 위해 잘 작동하고 아마도 당신을 위해 작동합니다.

데이터베이스에 비즈니스 기본 설정을 저장하기위한 테이블 (Biz_Config)이 있습니다. (필자가 IT 환경 설정이라고 부르는 web.config 섹션을 만들었습니다.)

나는 비즈니스 환경 설정을 관리하는 클래스가 있습니다. 생성자는 전체 테이블 (설정 당 하나의 행)을 가져 와서 사전에 복사하고 액세스 할 수있는 메소드 (예 : bizconfig.get ("key"))와이 사전을 업데이트하고 동시에 테이블을 업데이트합니다 . 또한 특정 사전 값에 대한 몇 가지 바로 가기 속성이 있습니다. 특히 값을 캐스팅해야하는 경우 (몇 가지 중요한 숫자가 있음). 그것은 아주 잘 작동합니다.

설정이 필요할 때마다 더 효율적으로 인스턴스화하지 않고 컨트롤러와 뷰에서 쉽게 액세스 할 수 있도록 전역 클래스를 만들었습니다.이 클래스는 상황을 벗어나는 것을 담당합니다. 세션 또는 응용 프로그램 변수 biz config 객체의 경우 응용 프로그램 변수를 검사하고 null이면 새 변수를 만듭니다. 그렇지 않으면 그냥 반환합니다. Globals는 나의 뷰에 사용할 수 있도록 내 web.config에 포함 된 내 도우미 네임 스페이스의 일부입니다. 그래서 나는 쉽게 전화 할 수있다 :

<% Globals.Biz_Config.Get("key") %> 

나는 이것이 도움이되기를 바란다. 코드를 원한다면, 내가 알아서 할 수 있습니다. 제임스

+0

답변을 주셔서 감사합니다. 비슷한 것을 생각해 냈습니다. 원래 질문으로 게시하겠습니다. –

관련 문제