How to fix ‘notnull type constraint is unavailable’ in .NET Standard 2.0 when implementing custom Microsoft.Extensions.Logging.ILogger interface?

  Kiến thức lập trình

I am implementing a custom SQL Server implementation of Microsoft.Extensions.Logging.ILogger. The NuGet package states that it is compatible with .NET Standard 2.0, so I added a class library to my solution targeting .NET Standard 2.0.

Using Visual Studio 2022, I added a new class implementing the ILogger interface and had Visual Studio implement the interface explicitly via the Quick Actions and Refactoring menu. It resulted in this code:

using Microsoft.Extensions.Logging;

internal class Foo : ILogger
{
    public IDisposable BeginScope<TState>(TState state) where TState : notnull
    { //                             (red squiggly line shows up here) ^^^^^^^
        throw new NotImplementedException();
    }

    public bool IsEnabled(LogLevel logLevel)
    {
        throw new NotImplementedException();
    }

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
    {
        throw new NotImplementedException();
    }
}

I am getting a compiler error with the notnull type constraint on the BeginScope method:

Error CS8370 – Feature ‘notnull generic type constraint’ is not available in C# 7.3. Please use language version 8.0 or greater.

My assumption was that I could create a custom implementation of ILogger in .NET Standard 2.0 since the NuGet package said it supports .NET Standard 2.0. A screenshot of the supported frameworks page for Microsoft.Extensions.Logging version 8.0.0 at NuGet.org is below:

My assumption must be incorrect. Maybe the target framework stated in the NuGet package pertains to using the package in an application rather than implementing an interface in the NuGet package?

Is there a way to implement Microsoft.Extensions.Logging.ILogger in a .NET Standard 2.0 project, or do I just need to target .NET 8+?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT