Skip to content

Instantly share code, notes, and snippets.

@rudiv
Created November 28, 2024 19:26
Show Gist options
  • Save rudiv/d8ed6dc5568fcc49742d90c193e7668b to your computer and use it in GitHub Desktop.
Save rudiv/d8ed6dc5568fcc49742d90c193e7668b to your computer and use it in GitHub Desktop.
LightEndpoints
using Microsoft.AspNetCore.Mvc;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddKeyedSingleton<Counter>("sng");
builder.Services.AddKeyedScoped<Counter>("scp");
builder.Services.AddScoped<EndpointAsAClass>();
builder.Services.AddScoped<EndpointWithARequest>();
var app = builder.Build();
app.MapEndpoint<EndpointAsAClass>("/");
app.MapEndpoint<EndpointWithARequest, string>("/{req}");
app.Run();
public interface IEndpoint
{
Task<IResult> RunAsync() => Task.FromResult<IResult>(TypedResults.Ok());
}
public interface IEndpoint<TRequest> : IEndpoint
{
Task<IResult> RunAsync(TRequest request);
}
public static class Mapper
{
public static void MapEndpoint<TEndpoint>(this WebApplication app, string pattern, string? method = default)
where TEndpoint : IEndpoint =>
app.MapMethods(pattern, [ method ?? HttpMethods.Get ], async (TEndpoint ep) => await ep.RunAsync());
public static void MapEndpoint<TEndpoint, TRequest>(this WebApplication app, string pattern, string? method = default)
where TEndpoint : IEndpoint<TRequest> =>
app.MapMethods(pattern, [ method ?? HttpMethods.Get ], async (TRequest req, [FromServices]TEndpoint ep) => await ep.RunAsync(req));
}
public class Counter
{
private int Count { get; set; }
public string County() => $"Count: {++Count}";
}
public class EndpointAsAClass([FromKeyedServices("sng")]Counter sng, [FromKeyedServices("scp")]Counter scp) : IEndpoint
{
public async Task<IResult> RunAsync()
{
return TypedResults.Ok($"Hello. Singleton: {sng.County()}. Scoped: {scp.County()}");
}
}
public class EndpointWithARequest : IEndpoint<string>
{
public async Task<IResult> RunAsync(string req)
{
return TypedResults.Ok($"Hello, {req}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment