“IServiceCollection”不包含“CustomMethod”的定义,并且没有可访问的扩展方法“CustomMethod”

问题描述 投票:0回答:1

我将代码放在单独的扩展方法中,但 ide 没有看到它。我收到下一个错误

'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?)
可能是什么原因?

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

如果我将该方法移至另一个类,那么一切都会正常。为什么?

c# dependency-injection extension-methods
1个回答
0
投票

对于扩展方法,包含它的类也必须标记为静态。有关更多信息,请查看此 - 如何实现和调用自定义扩展方法

© www.soinside.com 2019 - 2024. All rights reserved.