[英]Dependency injection has no value for non-static class and static method in c#
I have a code downloaded from AWS for Signature Version 4. Their code goes like this:我从 AWS 下载了签名版本 4 的代码。他们的代码是这样的:
public class PresignedUrl
{
public static void Run(string a, string b, string c)
{
}
}
I want to apply dependency injection in order for me to use the configuration service which was registered as singleton.我想应用依赖注入,以便我使用注册为单例的配置服务。 So it would turn out to be something like this:所以它会变成这样:
using MyNamespace.Services.Interfaces;
public class PresignedUrl
{
private static string _awsAccessKeyID;
private static string _awsSecretKey;
public PresignedUrl(IMyConfigurationService config)
{
_awsAccessKeyID = config.AWSAccessKeyID;
_awsSecretKey = config.AWSSecretKey;
}
public static void Run(string a, string b, string c)
{
}
}
But the issue is there's no value inside config.AWSAccessKeyID
and config.AWSSecretKey
.但问题是config.AWSAccessKeyID
和config.AWSSecretKey
没有值。 But in other non-static method it has.但在其他非静态方法中它有。 When I debug it, the 2 mentioned variable are null.当我调试它时,提到的 2 个变量为空。 How can I fixed it?我该如何解决?
If you have non-static constructor for PresignedUrl
, static fields _awsAccessKeyID
and _awsSecretKey
do not have values assigned until you run the code in the constructor.如果您有PresignedUrl
非静态构造PresignedUrl
,静态字段_awsAccessKeyID
和_awsSecretKey
不会分配值,直到您在构造函数中运行代码。
When you create PresignedUrl class instance, you can access _awsAccessKeyID
and _awsSecretKey
from both static and non-static methods:当您创建 PresignedUrl 类实例时,您可以从静态和非静态方法访问_awsAccessKeyID
和_awsSecretKey
:
PresignedUrl.Run("a", "b", "c");
var config = new MyConfigurationService
{
AWSAccessKeyID = "id",
AWSSecretKey = "key"
};
var instance = new PresignedUrl(config);
PresignedUrl.Run("a", "b", "c");
instance.NonStatiacRun("a", "b", "c");
Output:输出:
_awsAccessKeyID:
_awsSecretKey:
_awsAccessKeyID: id
_awsSecretKey: key
_awsAccessKeyID: id
_awsSecretKey: key
https://dotnetfiddle.net/Jz1hIB https://dotnetfiddle.net/Jz1hIB
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.