Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Fix After disabling automatic mapping, the mapping route is incomplete #562

Merged
merged 2 commits into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ public static IServiceCollection AddMasaMinimalAPIs(
var serviceProvider = services.BuildServiceProvider();
var serviceMapOptions = serviceProvider.GetRequiredService<IOptions<ServiceGlobalRouteOptions>>().Value;
var serviceTypes = TypeHelper.GetServiceTypes<ServiceBase>(serviceMapOptions.Assemblies.ToArray());

GlobalMinimalApiOptions.InitializeService();
foreach (var serviceType in serviceTypes)
{
GlobalMinimalApiOptions.AddService(serviceType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static void MapMasaMinimalAPIs(this WebApplication webApplication)
{
var serviceInstance = (ServiceBase)webApplication.Services.GetRequiredService(serviceType);
if (serviceInstance.RouteOptions.DisableAutoMapRoute ?? serviceMapOptions.DisableAutoMapRoute ?? false)
return;
continue;

serviceInstance.AutoMapRoute(serviceMapOptions, serviceMapOptions.Pluralization);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

[assembly: InternalsVisibleTo("Masa.Contrib.Service.MinimalAPIs.Tests")]

// ReSharper disable once CheckNamespace

namespace Masa.Contrib.Service.MinimalAPIs;
Expand All @@ -13,6 +15,11 @@ internal static class GlobalMinimalApiOptions
#pragma warning restore S2223
public static List<Type> ServiceTypes { get; private set; } = new();

public static void InitializeService()
{
ServiceTypes = new List<Type>();
}

public static void AddService(Type serviceType)
{
if (ServiceTypes.Contains(serviceType))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@
global using System.Linq;
global using System.Linq.Expressions;
global using System.Reflection;
global using System.Runtime.CompilerServices;
global using System.Threading;
Original file line number Diff line number Diff line change
Expand Up @@ -26,42 +26,107 @@ public void TestAddMultiServices()
[TestMethod]
public void AddService()
{
MasaApp.SetServiceCollection(_builder.Services);
var app = _builder.AddServices();
Assert.IsTrue(_builder.Services.Any(service
=> service.ServiceType == typeof(CustomService) && service.Lifetime == ServiceLifetime.Scoped));

var servicePrvider = _builder.Services.BuildServiceProvider();
var customService = servicePrvider.GetService<CustomService>();
var serviceProvider = _builder.Services.BuildServiceProvider();
var customService = serviceProvider.GetService<CustomService>();
Assert.IsNotNull(customService);

Assert.ReferenceEquals(customService.App, app);
Assert.AreEqual(customService.App, app);

Assert.ReferenceEquals(customService.Services, _builder.Services);
Assert.AreEqual(customService.Services, _builder.Services);

Assert.ThrowsException<MasaException>(() => customService.GetRequiredService<IServiceProvider>());

Assert.IsTrue(customService.GetTest2() == 1);

var newCustomService = servicePrvider.CreateScope().ServiceProvider.GetService<CustomService>();
var newCustomService = serviceProvider.CreateScope().ServiceProvider.GetService<CustomService>();
Assert.IsNotNull(newCustomService);

Assert.IsTrue(newCustomService.GetTest2() == 1);
}

[TestMethod]
public void TestMapMasaMinimalAPIs()
public void TestAddMasaMinimalApIs()
{
_builder.Services.AddMasaMinimalAPIs();
Assert.IsTrue(_builder.Services.Any<CatalogService>());
Assert.IsTrue(_builder.Services.Any<CustomService>());
Assert.IsTrue(_builder.Services.Any<GoodsService>());
Assert.IsTrue(_builder.Services.Any<UserService>());

var app = _builder.Build();
Assert.AreEqual(6, GlobalMinimalApiOptions.ServiceTypes.Count);
}

[TestMethod]
public void TestMapMasaMinimalApIs()
{
GlobalMinimalApiOptions.InitializeService();
GlobalMinimalApiOptions.AddService(typeof(PersonService));
GlobalMinimalApiOptions.AddService(typeof(GoodsService));

var builder = WebApplication.CreateBuilder();
builder.Services.Configure<ServiceGlobalRouteOptions>(options => options.DisableAutoMapRoute = false);
builder.Services.AddSingleton<PersonService>();
builder.Services.AddSingleton(_ => new GoodsService(builder.Services, ""));
var app = builder.Build();
app.MapMasaMinimalAPIs();

var service = (ServiceBase)app.Services.GetRequiredService(typeof(CatalogService));
Assert.AreEqual(app, service.App);
var routeBuilder = (IEndpointRouteBuilder)app;
var endpoints = routeBuilder.DataSources.SelectMany(x => x.Endpoints).ToList();
var group = GetServiceActionGroup(endpoints);
Assert.AreEqual(2, group.Count);
Assert.AreEqual(2, group[nameof(GoodsService)].Count);
Assert.AreEqual(1, group[nameof(PersonService)].Count);
}

#region Private Methods

private static Dictionary<string, List<string>> GetServiceActionGroup(List<Endpoint> endpoints)
{
Dictionary<string, List<string>> serviceRoutes = new(StringComparer.OrdinalIgnoreCase);
foreach (var endpoint in endpoints)
{
string serviceName = GetServiceName(endpoint);
if (!serviceRoutes.ContainsKey(serviceName))
{
serviceRoutes[serviceName] = new List<string>();
}

if (TryParseServiceActionName(endpoint, out string? actionName))
{
serviceRoutes[serviceName].Add(actionName);
}
}

return serviceRoutes;
}

private static bool TryParseServiceActionName(Endpoint endpoint, [NotNullWhen(true)] out string? actionName)
{
if (endpoint is not RouteEndpoint routeEndpoint)
{
actionName = null;
return false;
}

actionName = routeEndpoint.DisplayName ?? string.Empty;
return true;
}

private static string GetServiceName(Endpoint endpoint)
{
var metadata = endpoint.Metadata.GetMetadata<MethodInfo>();
Assert.IsNotNull(metadata);
return (object?)metadata.DeclaringType == null || IsCompilerGeneratedType(metadata.DeclaringType)
? ""
: metadata.DeclaringType.Name;
}

static bool IsCompilerGeneratedType(Type? type = null)
{
if ((object)type == null)
return false;
return Attribute.IsDefined((MemberInfo)type, typeof(CompilerGeneratedAttribute)) || IsCompilerGeneratedType(type.DeclaringType);
}

#endregion
}
Original file line number Diff line number Diff line change
Expand Up @@ -246,5 +246,4 @@ private static CustomServiceBase GetCatalogService()
=> new CatalogService();

#endregion

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ public CustomServiceBase(IServiceCollection services, string baseUri) : base(ser
}
#pragma warning restore CS0618

public string TestGetBaseUri(ServiceRouteOptions globalOptions) => base.GetBaseUri(globalOptions,
PluralizationService.CreateService(System.Globalization.CultureInfo.CreateSpecificCulture("en")));
public string TestGetBaseUri(ServiceRouteOptions globalOptions)
=> base.GetBaseUri(globalOptions, PluralizationService.CreateService(System.Globalization.CultureInfo.CreateSpecificCulture("en")));

public string TestGetMethodName(MethodInfo methodInfo, string prefix, ServiceRouteOptions globalOptions)
=> base.GetMethodName(methodInfo, prefix, globalOptions);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,18 @@ public GoodsService()

public GoodsService(IServiceCollection services, string baseUri) : base(services, baseUri)
{
RouteOptions.DisableAutoMapRoute = true;
App.MapGet("add", AddAsync);
App.MapGet("update", UpdateAsync);
}

private Task<IResult> AddAsync()
{
return Task.FromResult(Results.Accepted());
}

private Task<IResult> UpdateAsync()
{
return Task.FromResult(Results.Accepted());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,6 @@ public class OrderService : ServiceBase

public static string GetConnectionString => "connection string";

public int Id { private get; set; }

private int Age { get; set; }

public int CreateTime;

public OrderService() : base()
{

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

namespace Masa.Contrib.Service.MinimalAPIs.Tests.Services;

public class PersonService : ServiceBase
{
public PersonService()
{
RouteOptions.DisableAutoMapRoute = true;
App.MapGet("list", GetListAsync);
}

private Task GetListAsync()
{
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
// Copyright (c) MASA Stack All rights reserved.
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.

global using Masa.BuildingBlocks.Data;
global using Masa.Contrib.Service.MinimalAPIs.Tests.Services;
global using Microsoft.AspNetCore.Builder;
global using Microsoft.AspNetCore.Http;
global using Microsoft.AspNetCore.Routing;
global using Microsoft.AspNetCore.Mvc;
global using Microsoft.Extensions.DependencyInjection;
global using Microsoft.VisualStudio.TestTools.UnitTesting;
global using System.Diagnostics.CodeAnalysis;
global using System.Reflection;
global using System.Runtime.CompilerServices;