Implement endpoints with Services Dependency Injection.

**Note: This implementation is not in minimalAPI way and not optimized, expected to be changed soon.**

Add: `UserService` and its interface `IUserService`.

Fix: `UserEndpoint` is now in instance class style with DI to work.

Fix: change main program to work with above design.
This commit is contained in:
2025-07-07 15:54:44 +08:00
parent 1e4aaf33f9
commit 39b28386ae
3 changed files with 84 additions and 30 deletions

View File

@ -1,4 +1,5 @@
using System.Text.Json.Serialization;
using OptixServe.Core.Services;
using OptixServe.Api.Dtos;
namespace OptixServe.Api.Endpoints;
@ -8,25 +9,37 @@ namespace OptixServe.Api.Endpoints;
[JsonSerializable(typeof(IEnumerable<UserDto>))]
public partial class UserJsonContext : JsonSerializerContext { }
public static class UserEndpoint
public class UserEndpoint
{
public static IEnumerable<UserDto> GetUsers()
private readonly IUserService _userService;
// 通过构造函数注入依赖
public UserEndpoint(IUserService userService)
{
return [
new() {Id="1234", UserName = "xxx"},
new() {Id="5678", UserName = "yyy"},
];
_userService = userService;
}
public static void Register(WebApplication app)
{
var group = app.MapGroup("/users");
group.MapGet("/", GetAllUsers);
group.MapGet("/", (UserEndpoint endpoint) => endpoint.GetAllUsers());
group.MapGet("/{id}", (string id, UserEndpoint endpoint) => endpoint.GetUserById(id));
}
public static IResult GetAllUsers()
public IResult GetAllUsers()
{
return Results.Ok(GetUsers());
var users = _userService.GetUsers()
.Select(u => new UserDto { Id = u.Id, UserName = u.UserName });
return Results.Ok(users);
}
public IResult GetUserById(string id)
{
var user = _userService.GetUserById(id);
if (user == null)
return Results.NotFound();
return Results.Ok(new UserDto { Id = user.Id, UserName = user.UserName });
}
}