Implement endpoints in more flexible way.
Fix: re-implement `UserEndpoint` as static style which works best with minimal API, simplify the DI framework. Fix: remove no needed service register in main program.
This commit is contained in:
@ -9,34 +9,26 @@ namespace OptixServe.Api.Endpoints;
|
||||
[JsonSerializable(typeof(IEnumerable<UserDto>))]
|
||||
public partial class UserJsonContext : JsonSerializerContext { }
|
||||
|
||||
public class UserEndpoint
|
||||
public static class UserEndpoint
|
||||
{
|
||||
private readonly IUserService _userService;
|
||||
|
||||
// 通过构造函数注入依赖
|
||||
public UserEndpoint(IUserService userService)
|
||||
{
|
||||
_userService = userService;
|
||||
}
|
||||
|
||||
public static void Register(WebApplication app)
|
||||
{
|
||||
var group = app.MapGroup("/users");
|
||||
|
||||
group.MapGet("/", (UserEndpoint endpoint) => endpoint.GetAllUsers());
|
||||
group.MapGet("/{id}", (string id, UserEndpoint endpoint) => endpoint.GetUserById(id));
|
||||
group.MapGet("/", GetAllUsers);
|
||||
group.MapGet("/{id}", GetUserById);
|
||||
}
|
||||
|
||||
public IResult GetAllUsers()
|
||||
public static IResult GetAllUsers(IUserService userService)
|
||||
{
|
||||
var users = _userService.GetUsers()
|
||||
var users = userService.GetUsers()
|
||||
.Select(u => new UserDto { Id = u.Id, UserName = u.UserName });
|
||||
return Results.Ok(users);
|
||||
}
|
||||
|
||||
public IResult GetUserById(string id)
|
||||
public static IResult GetUserById(string id, IUserService userService)
|
||||
{
|
||||
var user = _userService.GetUserById(id);
|
||||
var user = userService.GetUserById(id);
|
||||
if (user == null)
|
||||
return Results.NotFound();
|
||||
|
||||
|
Reference in New Issue
Block a user