如何解决Autofac中的依赖?

时间:2014-11-02 20:07:13

标签: c# .net autofac

我有一个Serializar助手类,它会为我反序列化一些xml。我还有一个名为IStorageService的接口,它有两个实现。

这是我的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中解决此问题?

1 个答案:

答案 0 :(得分:2)

使用Autofac无法解决此问题。问题在于您的代码,C#编译器会告诉您错误。

问题是您的DeserializeXmlAsProductTypes方法是静态的,但您尝试访问实例字段。这在.NET中是不可能的,因此C#编译器会向您显示错误。

解决方案是使DeserializeXmlAsProductTypes实例方法,只需从方法定义中删除static关键字即可。

但是,这可能会导致应用程序中的其他代码失败,因为可能有一些代码依赖于此静态方法。如果是这种情况,这里的解决方案是将Serializar注入此类的构造函数中,以便失败的代码可以使用Serializar实例并调用新的DeserializeXmlAsProductTypes实例方法。

相关问题