当前位置: 欣欣网 > 码农

.NET 6 WebApplication 打造最小API

2024-05-15码农

前言

. NET 6 在 Preview4 时给我们带来了一个新的 API: WebApplication,通过这个API我们可以打造更小的轻量级API服务。

我们来尝试一下如何使用WebApplication设计一个小型API服务系统。

环境准备

.NET SDK v6.0.0-preview.6.21355.2

Visual Studio 2022 Preview

首先看看原始版本的WebApplication,官方已经提供了样例模板,打开我们的 VS 2022,选择新建项目选择ASP.NET Core empty,Framework选择.NET 6.0 (preview)点击创建,即可生成一个简单的最小代码示例:

如果我们在.csproj里在配置节PropertyGroup增加使用C#10新语法让自动进行类型推断来隐式的转换成委托,则可以更加精简:

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>preview</LangVersion>
</PropertyGroup>

当然仅仅是这样,是无法用于生产的,毕竟不可能所有的业务单元我们塞进这么一个小小的表达式里。不过借助WebApplication我们可以打造一个轻量级的系统,可以满足基本的依赖注入的小型服务。比如通过自定义特性类型,在启动阶段告知系统为哪些服务注入哪些访问路径,形成路由键和终结点。具体代码如下:

首先我们创建一个简易的特性类,只包含httpmethod和path:

[AttributeUsage(AttributeTargets.Method)]
public classWebRouter : Attribute
{
publicstring path;
public HttpMethod httpMethod;
publicWebRouter(string path)
{
this.path = path;
this.httpMethod = HttpMethod.Post;
}
publicWebRouter(string path, HttpMethod httpMethod)
{
this.path = path;
this.httpMethod = httpMethod;
}
}

接着我们按照一般的分层设计一套DEMO应用层/仓储服务:

publicinterfaceIMyService
{
Task<MyOutput> Hello(MyInput input);
}
publicinterfaceIMyRepository
{
Task<boolSaveData(MyOutput data);
}
public classMyService : IMyService
{
privatereadonly IMyRepository myRepository;
publicMyService(IMyRepository myRepository)
{
this.myRepository = myRepository;
}
[WebRouter("/", HttpMethod.Post)]
publicasync Task<MyOutput> Hello(MyInput input)
{
var result = new MyOutput() { Words = $"hello {input.Name ?? "nobody"}" };
await myRepository.SaveData(result);
returnawait Task.FromResult(result);
}
}
public classMyRepository : IMyRepository
{
publicasync Task<boolSaveData(MyOutput data)
{
Console.WriteLine($"保存成功:{data.Words}");
returnawait Task.FromResult(true);
}
}

最后我们需要将我们的服务接入到WebApplication的map里,怎么做呢?首先我们需要定义一套代理类型用来反射并获取到具体的服务类型。这里为了简单的演示,我只设计包含一个入参和没有入参的情况下:

publicabstract classDynamicPorxy
{
publicabstract Delegate Instance { getset; }
}
public classDynamicPorxyImpl<TsvcTimplTinputToutput> : DynamicPorxywhereTimpl :  classwhereTinput :  classwhereToutput :  class
{
publicoverride Delegate Instance { getset; }
publicDynamicPorxyImpl(MethodInfo method)
{
Instance = ([FromServices] IServiceProvider sp, Tinput input) => ExpressionTool.CreateMethodDelegate<Timpl, Tinput, Toutput>(method)(sp.GetService(typeof(Tsvc)) as Timpl, input);
}
}
public classDynamicPorxyImpl<TsvcTimplToutput> : DynamicPorxywhereTimpl :  classwhereToutput :  class
{
publicoverride Delegate Instance { getset; }
publicDynamicPorxyImpl(MethodInfo method)
{
Instance = ([FromServices] IServiceProvider sp) => ExpressionTool.CreateMethodDelegate<Timpl, Toutput>(method)(sp.GetService(typeof(Tsvc)) as Timpl);
}
}

接着我们创建一个代理工厂用于创建服务的方法委托并创建代理类型实例返回给调用端

public classDynamicPorxyFactory
{
publicstatic IEnumerable<(WebRouter, DynamicPorxy)> RegisterDynamicPorxy()
{
foreach (var methodinfo in DependencyContext.Default.CompileLibraries.Where(x => !x.Serviceable && x.Type != "package")
.Select(x => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(x.Name)))
.SelectMany(x => x.GetTypes().Where(x => !x.IsInterface && x.GetInterfaces().Any()).SelectMany(x => x.GetMethods().Where(y => y.CustomAttributes.Any(z => z.AttributeType == typeof(WebRouter))))))
{
var webRouter = methodinfo.GetCustomAttributes(typeof(WebRouter), false).FirstOrDefault() as WebRouter;
DynamicPorxy dynamicPorxy;
if (methodinfo.GetParameters().Any())
dynamicPorxy = Activator.CreateInstance(typeof(DynamicPorxyImpl<,,,>).MakeGenericType(methodinfo.DeclaringType.GetInterfaces()[0], methodinfo.DeclaringType, methodinfo.GetParameters()[0].ParameterType , methodinfo.ReturnType), newobject[] { methodinfo }) as DynamicPorxy;
else
dynamicPorxy = Activator.CreateInstance(typeof(DynamicPorxyImpl<,,>).MakeGenericType(methodinfo.DeclaringType.GetInterfaces()[0], methodinfo.DeclaringType, methodinfo.ReturnType), newobject[] { methodinfo }) as DynamicPorxy;
yieldreturn (webRouter, dynamicPorxy);
}
}
}

internal classExpressionTool
{
internalstatic Func<TObj, Tin, Tout> CreateMethodDelegate<TObj, Tin, Tout>(MethodInfo method)
{
var mParameter = Expression.Parameter(typeof(TObj), "m");
var pParameter = Expression.Parameter(typeof(Tin), "p");
var mcExpression = Expression.Call(mParameter, method, Expression.Convert(pParameter, typeof(Tin)));
var reExpression = Expression.Convert(mcExpression, typeof(Tout));
return Expression.Lambda<Func<TObj, Tin, Tout>>(reExpression, mParameter, pParameter).Compile();
}
internalstatic Func<TObj, Tout> CreateMethodDelegate<TObj, Tout>(MethodInfo method)
{
var mParameter = Expression.Parameter(typeof(TObj), "m");
var mcExpression = Expression.Call(mParameter, method);
var reExpression = Expression.Convert(mcExpression, typeof(Tout));
return Expression.Lambda<Func<TObj, Tout>>(reExpression, mParameter).Compile();
}
}

最后我们创建WebApplication的扩展方法来调用代理工厂以及注入IOC容器:

publicstatic classWebApplicationBuilderExtension
{
static Func<string, Delegate, IEndpointConventionBuilder> GetWebApplicationMap(HttpMethod httpMethod, WebApplication webApplication) => (httpMethod) switch
{
(HttpMethod.Get) => webApplication.MapGet,
(HttpMethod.Post) => webApplication.MapPost,
(HttpMethod.Put) => webApplication.MapPut,
(HttpMethod.Delete) => webApplication.MapDelete,
_ => webApplication.MapGet
};
publicstatic WebApplication RegisterDependencyAndMapDelegate(this WebApplicationBuilder webApplicationBuilder, Action<IServiceCollection> registerDependencyAction, Func<IEnumerable<(WebRouter webRouter, DynamicPorxy dynamicPorxy)>> mapProxyBuilder)
{
webApplicationBuilder.Host.ConfigureServices((ctx, services) =>
{
registerDependencyAction(services);
});
var webApplication = webApplicationBuilder.Build();
mapProxyBuilder().ToList().ForEach(item => GetWebApplicationMap(item.webRouter.httpMethod, webApplication)(item.webRouter.path, item.dynamicPorxy.Instance));
return webApplication;
}
}

当然包括我们的自定义容器注入方法:

public classMyServiceDependency
{
publicstaticvoidRegister(IServiceCollection services)
{
services.AddScoped<IMyService, MyService>();
services.AddScoped<IMyRepository, MyRepository>();
}
}

最后改造我们的program.cs的代码,通过扩展来注入容器和代理委托并最终生成路由-终结点:

await WebApplication.CreateBuilder().RegisterDependencyAndMapDelegate(MyServiceDependency.Register,DynamicPorxyFactory.RegisterDynamicPorxy).RunAsync("http://*:80");

这样这套小型API系统就基本完成了,可以满足日常的依赖注入和独立的业务单元类型编写,最后我们启动并调用一下,可以看到确实否符合我们的预期成功的调用到了应用服务并且仓储也被正确的执行了:

转自:a1010

链接:cnblogs.com/gmmy/p/14990077.html