繁体   English   中英

如何解决Autofac中的依赖关系?

[英]How to Resolve dependency in 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中解决此问题?

您无法使用Autofac解决此问题。 问题出在您的代码中,C#编译器告诉您出了什么问题。

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM