2014-11-02 72 views
1

我有一個Serializar幫助器類,它會爲我反序列化一些xml。我也有一個名爲IStorageService的接口,它有兩個實現。如何解決Autofac中的依賴關係?

這裏是我的IStorageService接口:

public interface IStorageService 
    { 
     string GetFullImageUri(string fileName); 
    } 

下面是兩種實現:

1-

public class AzureBlobStorageService : IStorageService 
    { 
     private readonly string _rootPath; 
     public string GetFullImageUri(string fileName) 
     { 
      return _rootPath + fileName; 
     } 
    } 

2-

public class FileSystemStorageService : IStorageService 
    {  
     public string GetFullImageUri(string fileName) 
     { 
      return _applicationPath + "/Data/Images/"+ fileName; 
     } 
    } 

這裏是我Serializar類

public class Serializar 
    { 
     private readonly IStorageService _storageService; 

     public Serializar(IStorageService storageService) 
     { 
      _storageService = storageService; 
     } 
     public static List<ProductType> DeserializeXmlAsProductTypes(object xml) 
     { 
      // do stuff here. 

      // this method require using _storageService.GetFullImageUri(""); 
     } 
    } 

我得到這個編譯錯誤:

錯誤32的對象引用需要非靜態字段,方法或屬性「Serializar._storageService

如何在解決這個使用Autofac的IocConfig.cs?

回答

2

你不能用Autofac來解決這個問題。問題出在你的代碼中,C#編譯器告訴你什麼是錯的。

問題是您的DeserializeXmlAsProductTypes方法是靜態的,但您嘗試訪問實例字段。這在.NET中是不可能的,因此C#編譯器會向您提供一個錯誤。

解決的辦法是使DeserializeXmlAsProductTypes成爲實例方法,只需從方法定義中刪除static關鍵字即可。

但是,這可能會導致應用程序中的其他代碼失敗,因爲可能有一些代碼依賴於此靜態方法。如果是這種情況,這裏的解決方案是將Serializar注入到此類的構造函數中,以便失敗的代碼可以使用Serializar實例並調用新的DeserializeXmlAsProductTypes實例方法。

+0

如果我這樣做,並調用DeserializeXmlAsProductTypes()方法。它不會拋出_storageService爲空或未被引用的異常? – user123456 2014-11-02 20:25:49

+0

@Mohammadjouhari,不會,因爲你會確保'Serializar'是由Autofac註冊和解決的。在這種情況下,Autofac會爲您注入'IStorageService'。 – Steven 2014-11-02 21:28:42