'ASP.NET Core Web API - How to resolve Field 'MyService._config' is never assigned to, and will always have its default value null

I have this code in ASP.NET Core-6 Web API.

Service:

public class MyService : IMyService
{
    private readonly HttpHelper _httpHelper;
    private readonly IConfiguration _config;
    private readonly ILogger<MyService> _logger;
    private readonly IDataUtil _dataAccess;
    private readonly IMemoryCache _cache;

    public MyService(HttpHelper httpHelper,
        IConfiguration config,
        ILogger<MyService> logger,
        IDataUtil dataAccess,
        IMemoryCache cache
        )
    {
        _httpHelper = httpHelper;
        _config = config;
        _logger = logger;
        _dataAccess = dataAccess;
        _cache = cache;
    }

    public async Task<BaseResponse> StatusQuery(statusQueryRequest request)
    {
        var response = new BaseResponse();
        try
        {
            var token = await FetchToken();
            var headers = new Dictionary<string, string>();
            headers.Add("Authorization", $"Bearer {token.access_token}");
            request.data_key = token.data.vpay_institution.data_key;

            var statusQuery = baseUrl + _config.GetSection("MyEndpoints").GetValue<string>("tokenStatusQuery");
            var httpResponse = _httpHelper.PostOrPutRequest(uri: statusQuery, methodType: HttpMethod.Post, model: request, headers: headers).Result;
            if (httpResponse != null)
            {
                if (httpResponse.StatusCode == HttpStatusCode.OK)
                {
                    var content = await httpResponse.Content.ReadAsStringAsync();
                    response = JsonConvert.DeserializeObject<MyStatusQueryResponse>(content);
                }
            }
        }
        catch (Exception ex)
        {
            _logger.LogError("An Error occured " + ex.ToString());
        }

        return response;
    }
}

I got this warning:

Warning CS0649 Field 'MyService._config' is never assigned to, and will always have its default value null

_config is highlighted in private readonly IConfiguration _config;

Why is the warning there when I have already applied _config and how do I get it resolved?

Thanks



Solution 1:[1]

You can do this tho:

def result(self):
        states = States()
        
        x = []
        
        for i in [states.state1,states.state2]: # changed state1 to states.state1 and so on
            state_result = i()
            x.append(state_result)
            
        return x

Solution 2:[2]

I think you can use lambda. Here, i made a simple example for you.

def foo(text):
    print(text)
        
            
a = [lambda: foo("hey"), lambda: foo("boo")]
for i in a:
    i()

Result:

hey
boo

In your case, you should come over with this:

for i in [lambda: state1(), lambda:state2()]:
    state_result = i()
    x.append(state_result)

But if you ask my opinion, it's important to inform you that calling functions through a list is not a healthy way. A software languge usually has a solution for many cases; but in this case, i think your point of view is wrong. Doing work by messing with built-in techniques and trying to find some secret tricks is is not a suggested thing.

Solution 3:[3]

The clean way to do this is to "register" your state methods. SOmething like this:

class States():
    states = []
    def register_state(cache):
        def inner(fn):
            cache.append(fn)
        return inner
    
    @register_state(states)
    def state1(self):
        a = 2*10
        return a
        
    @register_state(states)
    def state2(self):
        a = 50/10
        return a

Then your Results class can do

class Results:
    def __init__(self):
        pass
    
    def result(self):
        states = States()
        
        x = []
        
        for i in states.states:
            state_result = i(states)
            x.append(state_result)
            
        return x

Solution 4:[4]

You can get the members of class States via the class' dict as:

States.__dict__

Which'll give you all the attributes and function of your class as:

{'__module__': '__main__', '__init__': <function States.__init__ at 0x00000183066F0A60>, 'state1': <function States.state1 at 0x00000183066F0AF0>, 'state2': <function States.state2 at 0x000001830 ...

You can filter this into a list comprehension dict to not include dunders as:

[funcname for funcname in States.__dict__ if not (str.startswith('__') and str.endswith('__'))]

This will return you a list of member functions as:

['state1', 'state2']

Then create an object of States as:

states = States()

get the whole calculation done as:

for funcname in [funcname for funcname in States.__dict__ if not (funcname.startswith('__') and funcname.endswith('__'))]:
    x.append(States.__dict__[funcname](states))

Better yet, make it a comprehension as:

[States.__dict__[funcname](states) for funcname in States.__dict__ if not (funcname.startswith('__') and funcname.endswith('__'))]

Your answer after applying this approach is: [20, 5.0]

or get the dict of functionName and returnValues as a comprehension:

{funcname: States.__dict__[funcname](states) for funcname in States.__dict__ if not (funcname.startswith('__') and funcname.endswith('__'))}

Which'll give you an output as:

{'state1': 20, 'state2': 5.0}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Soyokaze
Solution 2 Meliksah Bozkurt
Solution 3 RoadieRich
Solution 4