2011-04-19 300 views
1

鑑於以下兩個類別,我可以將ApplicationSettings映射到AppSettings嗎?AutoMapper可以映射靜態屬性嗎?

Mapper.CreateMap(Of ApplicationSettings, AppSettings)() 
Mapper.Map(Of ApplicationSettings, AppSettings)(ApplicationSetting.Load) 

Public Class ApplicationSettings 

    Public Property RecaptchaPrivateKey As String 
    Public Property RecaptchaPublicKey As String 

End Class 

Public Class AppSettings 

    Public Shared Property RecaptchaPrivateKey As String 
    Public Shared Property RecaptchaPublicKey As String 

End Class 
+2

爲什麼這裏有兩個班?靜態方法對源類加載,然後對靜態屬性進行加載。第二類在第一類中提供的靜態屬性不是什麼? – 2011-04-20 00:49:34

+0

@Jimmy - 源類沒有靜態屬性。我使用XmlSerializer來序列化/反序列化一些應用程序級別的設置,我想在整個應用程序中使用它,並且我可以使用Application狀態,但它不是強類型的,所以我認爲這對於AutoMapper來說是完美的地方。無論如何,它似乎不會將ApplicationSettings類屬性映射到AppSettings的靜態屬性。 – Sam 2011-04-20 04:49:08

+0

您應該可以將AppSettings更改爲單例,然後將ApplicationSettings映射到AppSettings.Instance ..我將無法爲您提供代碼,因爲我不太瞭解VB.NET語法:) – 2011-04-20 07:19:50

回答

1

薩姆問這在C#,這裏有雲:

public class AppSettings 
{ 
    public string RecaptchaPrivateKey { get; set; } 
    public string RecaptchaPublicKey { get; set; } 
} 

public class ApplicationSettings 
{ 
    private static ApplicationSettings _instance; 

    public static ApplicationSettings Instance 
    { 
     get { 
      if (_instance == null) { _instance = new ApplicationSettings();}     
      return _instance; 
     } 
    } 

    public string RecaptchaPrivateKey { get; set; } 
    public string RecaptchaPublicKey { get; set; } 

    private ApplicationSettings() 
    { 
    } 
} 

,並使用此:

Mapper.CreateMap<ApplicationSettings, AppSettings>(); 
var appSettings = Mapper.Map<ApplicationSettings, AppSettings>ApplicationSettings.Instance); 
+0

這並不回答提出的問題,它提出了對代碼庫進行更改以解決問題(創建單例)。它解決了這個人的特定問題,但它並沒有回答關於AutoMapper是否可以處理靜態屬性的更一般的問題。 – 2015-02-09 16:26:55