2014-11-02 69 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