[英]Static Method of a Static Class vs. Static Method of a Non-Static Class ( C# )
[英]Dependency injection has no value for non-static class and static method in c#
我從 AWS 下載了簽名版本 4 的代碼。他們的代碼是這樣的:
public class PresignedUrl
{
public static void Run(string a, string b, string c)
{
}
}
我想應用依賴注入,以便我使用注冊為單例的配置服務。 所以它會變成這樣:
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)
{
}
}
但問題是config.AWSAccessKeyID
和config.AWSSecretKey
沒有值。 但在其他非靜態方法中它有。 當我調試它時,提到的 2 個變量為空。 我該如何解決?
如果您有PresignedUrl
非靜態構造PresignedUrl
,靜態字段_awsAccessKeyID
和_awsSecretKey
不會分配值,直到您在構造函數中運行代碼。
當您創建 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");
輸出:
_awsAccessKeyID:
_awsSecretKey:
_awsAccessKeyID: id
_awsSecretKey: key
_awsAccessKeyID: id
_awsSecretKey: key
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.