How to dispose IConfiguration in an ASP.NET Core application

REDDY Harika 1 Reputation point
2023-10-30T10:02:32.35+00:00

I have a .NET core solution for APIs catering to a mobile application.

In that I am using IConfiguration service to read the config (IConfiguration config = new ConfigurationBuilder().AddJsonFile(ModelConstants.SettingFile).Build();)

This is working but while running coverity test it is throwing an error with resource leak.

ConfigurationBuilder doesn't have Dispose.

.NET
.NET
Microsoft Technologies based on the .NET software framework.
2,284 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
3,756 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,427 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 106.3K Reputation points
    2023-10-30T11:22:58.5333333+00:00

    If the config object must be disposed when it is disposable, try something like this:

    IConfiguration config = new ConfigurationBuilder( ).AddJsonFile( ModelConstants.SettingFile ).Build( );
    using( config as IDisposable )
    {
       . . .
    }
    
    0 comments No comments