Search code examples
c#extension-methods

'IServiceCollection' does not contain a definition for 'CustomMethod' and no accessible extension method 'CustomMethod'


I put the code in a separate extending method, but ide doesn't see it. I'm getting next error 'IServiceCollection' does not contain a definition for 'AddSwagger' and no accessible extension method 'AddSwagger' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?) What could be the reason?

public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddControllers();
        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwagger();
        builder.Services.AddProblemDetails();

        ...
    }

    public static IServiceCollection AddSwagger(this IServiceCollection services)
    {
        return services.AddSwaggerGen(options =>
        {
            options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
            {
                Description = "Standard Authorization header using the Bearer scheme (\"Bearer {token}\")",
                In = ParameterLocation.Header,
                Name = "Authorization",
                Type = SecuritySchemeType.ApiKey
            });

            options.OperationFilter<SecurityRequirementsOperationFilter>();
        });
    }
}

If I move the method to another class, then everything works fine. Why?


Solution

  • For an extension method, the class containing it also has to be marked as static.

    From your example it appears that the AddSwagger method is within Program class which isn't marked static. You would need to move the AddSwagger method to another class that is marked static.

    public static class SwaggerExtensions
    {
        public static IServiceCollection AddSwagger(this IServiceCollection services)
        {
          // your logic here 
        }
    }
    

    For more information look at this - How to implement and call a custom extension method