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

Time:07-13

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

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

You should assign the _logger object to the implementation either from constructor and using some DI Container.

CodePudding user response:

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

CodePudding user response:

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;
    }
}

}

  • Related