Why do I get this error in the static class ? -> Readonly field _logger is never assigned

443 views Asked by At

I am using ILogger in my static class.

The codes in the class shown in below:

internal static class LicenceSetter
{
    private static ILogger _logger;

    internal static void WorkWithStream(Action<Stream> setLicence, string name = null)
    {
        try
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            var declaringType = MethodBase.GetCurrentMethod().DeclaringType;
            Debug.Assert(declaringType != null, "declaringType != null");

            name = name ?? $"{declaringType.Namespace}.{AsposeTotalLic2017FileName}";

            using (Stream stream = assembly.GetManifestResourceStream(name))
            {
                setLicence(stream);
            }
        }
        catch (Exception exception)
        {
            _logger.LogError(exception,"Error loading embedded resource for aspose licence");
            Trace.TraceError("Error loading embedded resource for aspose licence");
            throw;
        }
    }
}

But I get this error while building the application: Readonly field _logger is never assigned

5

There are 5 answers

0
otreblA On

I don't see where your logger is being assigned in that class. You may be getting a null reference exception by accessing the object.

2
Ben On

You have not set it to anything. Consider using dependency injection and inject it through the constructor

1
Lokendra chand On

You should assign the _logger object to the implementation either from the constructor and/or by using some Dependency Injection (DI) Container.

0
verticalPacked On

As allready mentioned the variable is not assigned in that class.

To handle injection within your static class, check this post out, on how to deal with that. (e.g. with method injection)

https://stackoverflow.com/a/55244379

0
Masoud On

ILogger property should not be static.

I found a solution for that:

internal static class LicenceSetter
{

//Removed - private static ILogger _logger;

internal static void WorkWithStream(ILogger logger,Action<Stream> setLicence, string name = null)
{
    try
    {
        Assembly assembly = Assembly.GetExecutingAssembly();
        var declaringType = MethodBase.GetCurrentMethod().DeclaringType;
        Debug.Assert(declaringType != null, "declaringType != null");

        name = name ?? $"{declaringType.Namespace}.{AsposeTotalLic2017FileName}";

        using (Stream stream = assembly.GetManifestResourceStream(name))
        {
            setLicence(stream);
        }
    }
    catch (Exception exception)
    {
        logger.LogError(exception,"Error loading embedded resource for aspose licence");
        Trace.TraceError("Error loading embedded resource for aspose licence");
        throw;
    }
}

}