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
Answers
ILogger property should not be static.
I found a solution for that:
}
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.
You have not set it to anything. Consider using dependency injection and inject it through the constructor
You should assign the
_logger
object to the implementation either from the constructor and/or by using some Dependency Injection (DI) Container.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