我有一個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?
如果我這樣做,並調用DeserializeXmlAsProductTypes()方法。它不會拋出_storageService爲空或未被引用的異常? – user123456 2014-11-02 20:25:49
@Mohammadjouhari,不會,因爲你會確保'Serializar'是由Autofac註冊和解決的。在這種情況下,Autofac會爲您注入'IStorageService'。 – Steven 2014-11-02 21:28:42