简体   繁体   中英

Using Extension in ASP.NET application - .NET 6

I'm trying to get NEST working in an ASP.NET application. I'm following the guide https://blexin.com/en/blog-en/how-to-integrate-elasticsearch-in-asp-net-core/#highlighter_541789 . I'm trying to figure out how to call AddElasticsearch correctly on the builder. I've tried a few ways but keep getting compiler complaints.

Extensions.cs

public static class Extensions
{
    public static void AddElasticsearch(this IServiceCollection services, IConfiguration configuration)
    {
        var url = configuration["elasticsearch:url"];
        var defaultIndex = configuration["elasticsearch:index"];

        var settings = new ConnectionSettings(new Uri(url)).DefaultIndex(defaultIndex);

        AddDefaultMappings(settings);

        var client = new ElasticClient(settings);

        services.AddSingleton(client);

        CreateIndex<LegiscanModelBill>(client, defaultIndex);
    }

    private static void AddDefaultMappings(ConnectionSettings settings) => settings.DefaultMappingFor<LegiscanModelBill>(m => m);

    // private static void CreateIndex<T>(IElasticClient client, string indexName)
    // {
    //     var createIndexResponse = client.Indices.Create(indexName,
    //         index => index.Map<LegiscanModelBill>(x => x.AutoMap())
    //     );
    // }

    private static void CreateIndex<T>(ElasticClient client, string indexName) where T : class
    {
        client.Indices.Create($"{indexName}_{typeof(T).ToString}", i => i.Map<T>(m => m.AutoMap()));
    }
}

Program.cs

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddElasticsearch(options => options.configuration)
    .AddGraphQLServer()
    .AddQueryType<Query>();


var app = builder.Build();

app.MapGraphQL();

app.Run();

compiler error

Cannot convert lambda expression to type 'IConfiguration' because it is not a delegate type 

Instead of options => options.configuration which is just a random guess with no meaning, use builder.Configuration .

To be honest, I think that this new way of having a main method and not actually having a main method is hiding so much that it doesn't make it "easier", it actually makes it harder to understand what is actually happening. Because it's all hidden. Anyway, that is what you need to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM