WMSlite/WmsLite.Api/Infrastructure/ServiceCollectionExtensions.cs
zhougf fa1b286463 Add WmsLite monorepo with JWT auth, tenant context, and project READMEs.
Implement API security baseline (sys_user, JWT, audit fields, transactions,
unique constraints) and Web real login with 401 handling. Document setup
and development workflows in root, WmsLite.Api, and WmsLite.Web README files.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-24 14:17:47 +08:00

60 lines
2.2 KiB
C#

using System.Reflection;
using System.Runtime.CompilerServices;
using WmsLite.Api.Repositories;
using WmsLite.Api.Repositories.Interfaces;
namespace WmsLite.Api.Infrastructure;
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddWmsLiteServices(this IServiceCollection services)
{
services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
services.AddScoped<ITransactionRunner, SqlSugarTransactionRunner>();
services.RegisterByConvention(
typeof(ServiceCollectionExtensions).Assembly,
"WmsLite.Api.Repositories.Interfaces",
"WmsLite.Api.Repositories");
services.RegisterByConvention(
typeof(ServiceCollectionExtensions).Assembly,
"WmsLite.Api.Services.Interfaces",
"WmsLite.Api.Services");
return services;
}
private static IServiceCollection RegisterByConvention(
this IServiceCollection services,
Assembly assembly,
string interfaceNamespace,
string implementationNamespace)
{
var implementationTypes = assembly.GetTypes()
.Where(type => type is { IsClass: true, IsAbstract: false }
&& type.Namespace == implementationNamespace
&& !type.IsNested
&& type.GetCustomAttribute<CompilerGeneratedAttribute>() is null)
.ToDictionary(type => type.Name, StringComparer.Ordinal);
var interfaceTypes = assembly.GetTypes()
.Where(type => type is { IsInterface: true, IsGenericTypeDefinition: false }
&& type.Namespace == interfaceNamespace
&& type.GetCustomAttribute<CompilerGeneratedAttribute>() is null);
foreach (var interfaceType in interfaceTypes)
{
var implementationName = interfaceType.Name.StartsWith('I')
? interfaceType.Name[1..]
: interfaceType.Name;
if (implementationTypes.TryGetValue(implementationName, out var implementationType)
&& interfaceType.IsAssignableFrom(implementationType))
{
services.AddScoped(interfaceType, implementationType);
}
}
return services;
}
}