dotnet webapi miniapi 依赖注入

发布时间 2024-01-07 21:27:12作者: 虎虎生威啊

原先的模式

GamesEndpoints.cs

public static class GamesEndpoints
{
    public static RouteGroupBuilder MapGamesEndpoints(this IEndpointRouteBuilder endpoints)
    {
        // 自动创建一个实例,然后使用
        InMemGamesRepository repository = new();
        var group = endpoints.MapGroup("/games").WithParameterValidation();
        group.MapGet("/", () => repository.GetAll());
        return group;
    }
}

InMemGamesRepository.cs

using GameStore.Api.Entities;
namespace GameStore.Api.Repositoriesa;

public class InMemGamesRepository 
{
    private readonly List<Game> games = new()
    {
        new Game(){
            Id = 1,
            Name="Street Fighter II",
            Genre ="Fighting",
            Price = 19.99M,
            ReleaseDate = new DateTime(1991,2,1),
            ImgUri = "https://palcehold.co/100"
        },
        new Game(){
            Id = 2,
            Name="FIFA 23",
            Genre ="Sports",
            Price = 29.99M,
            ReleaseDate = new DateTime(2022,2,1),
            ImgUri = "https://palcehold.co/100"
        },

};

    public IEnumerable<Game> GetAll()
    {
        return games;
    }
    public Game? Get(int id)
    {
        return games.Find(game => game.Id == id);
    }
    public void Create(Game game)
    {
        game.Id = games.Max(game => game.Id) + 1;
        games.Add(game);
    }
    public void Update(Game updatedGame)
    {
        var index = games.FindIndex(game => game.Id == updatedGame.Id);
        games[index] = updatedGame;
    }
    public void Delete(int id)
    {
        var index = games.FindIndex(game => game.Id == id);
        games.RemoveAt(index);
    }

}

现在的模式

GamesEndpoints.cs


using System.Diagnostics.CodeAnalysis;
using System.Reflection.Metadata;
using GameStore.Api.Entities;
using GameStore.Api.Repositoriesa;

namespace GameStore.Api.Endpoints;

public static class GamesEndpoints
{

    const string GetGameEndpointName = "GetGame";
    public static RouteGroupBuilder MapGamesEndpoints(this IEndpointRouteBuilder endpoints)
    {

        var group = endpoints.MapGroup("/games").WithParameterValidation();

        // 直接依赖注入
        group.MapGet("/", (IGamesRepository repository) => repository.GetAll());

        group.MapGet("/{id}", (IGamesRepository repository,int id) =>
        {
            Game? game = repository.Get(id);
            if (game is null)
            {
                return Results.NotFound();
            }
            return Results.Ok(game);
        }).WithName(GetGameEndpointName);

        group.MapPut("/{id}", (IGamesRepository repository,int id, Game updatedGame) =>
        {

            Game? existingGame = repository.Get(id);
            if (existingGame is null)
            {
                return Results.NotFound();
            }
            existingGame.Name = updatedGame.Name;
            existingGame.Genre = updatedGame.Genre;
            existingGame.Price = updatedGame.Price;
            existingGame.ReleaseDate = updatedGame.ReleaseDate;
            existingGame.ImgUri = updatedGame.ImgUri;

            repository.Update(existingGame);

            return Results.NoContent();
        });

        group.MapDelete("/{id}", (IGamesRepository repository,int id) =>
        {
            Game? game = repository.Get (id);
            if (game is not null)
            {
                repository.Delete(id);
            }
            return Results.NoContent();
        });


        return group;

    }

}

对比

手动实例化

InMemGamesRepository repository = new();
group.MapGet("/", () => repository.GetAll());

依赖注入

依赖注入:

group.MapGet("/", (IGamesRepository repository) => repository.GetAll());

注册服务:
只有在builder中注册了服务,上面的接口在访问的时候才会自动帮你实例化.

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<IGamesRepository, InMemGamesRepository>();
// builder.Services.AddScoped<IGamesRepository, InMemGamesRepository>();