Dependency injection has no value for non-static class and static method in c#

Viewed 516

I have a code downloaded from AWS for Signature Version 4. Their code goes like this:

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. But in other non-static method it has. When I debug it, the 2 mentioned variable are null. How can I fixed it?

1 Answers

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.

When you create PresignedUrl class instance, you can access _awsAccessKeyID and _awsSecretKey from both static and non-static methods:

        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

Related