[英]How to Resolve dependency in Autofac?
I have a Serializar helper class that will deserialize some xml for me. 我有一个Serializar帮助器类,它将为我反序列化一些xml。 I also have an Interface called IStorageService that has two implementation.
我还有一个名为IStorageService的接口,该接口有两个实现。
here is my IStorageService interface : 这是我的IStorageService接口:
public interface IStorageService
{
string GetFullImageUri(string fileName);
}
Here is the two implementation : 这是两个实现:
1- 1-
public class AzureBlobStorageService : IStorageService
{
private readonly string _rootPath;
public string GetFullImageUri(string fileName)
{
return _rootPath + fileName;
}
}
2- 2-
public class FileSystemStorageService : IStorageService
{
public string GetFullImageUri(string fileName)
{
return _applicationPath + "/Data/Images/"+ fileName;
}
}
Here is my Serializar class 这是我的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("");
}
}
I am getting this compiling error : 我收到此编译错误:
Error 32 An object reference is required for the non-static field, method, or property 'Serializar._storageService 错误32非静态字段,方法或属性'Serializar._storageService需要对象引用
How to resolve this in the IocConfig.cs using Autofac ? 如何使用Autofac在IocConfig.cs中解决此问题?
You can't solve this with Autofac. 您无法使用Autofac解决此问题。 The problem is in your code and the C# compiler tells you what's wrong.
问题出在您的代码中,C#编译器告诉您出了什么问题。
The problem is that your DeserializeXmlAsProductTypes
method is static, but you try to access instance field. 问题是您的
DeserializeXmlAsProductTypes
方法是静态的,但是您尝试访问实例字段。 This is not possible in .NET and the C# compiler therefore presents you with an error. 在.NET中这是不可能的,因此C#编译器会向您显示错误。
The solution is to make the DeserializeXmlAsProductTypes
an instance method, simply by removing the static
keyword from the method definition. 解决方案是使
DeserializeXmlAsProductTypes
成为实例方法,只需从方法定义中删除static
关键字即可。
This might however cause other code in your application to fail, because there might be some code that depends on this static method. 但是,这可能会导致应用程序中的其他代码失败,因为可能有一些代码依赖于此静态方法。 If this is the case, the solution here is to inject the
Serializar
into the constructor of such class, so that the failing code can make use of the Serializar
instance and call the new DeserializeXmlAsProductTypes
instance method. 如果是这种情况,这里的解决方案是将
Serializar
注入到此类的构造函数中,以便失败的代码可以使用Serializar
实例并调用新的DeserializeXmlAsProductTypes
实例方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.