使用.Net6中的WebApplication打造最小API

网友投稿 274 2022-06-07


.net6在preview4时给我们带来了一个新的API:WebApplication,通过这个API我们可以打造更小的轻量级API服务。今天我们来尝试一下如何使用WebApplication设计一个小型API服务系统。

环境准备

.NETSDK v6.0.0-preview.5.21355.2 Visual Studio 2022 Preview

首先看看原始版本的WebApplication,官方已经提供了样例模板,打开我们的vs2022,选择新建项目选择asp.net core empty,framework选择.net6.0(preview)点击创建,即可生成一个简单的最小代码示例:

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

net6.0 preview

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

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

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

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

public interface IMyService { Task Hello(MyInput input); } public interface IMyRepository { Task SaveData(MyOutput data); } public class MyService : IMyService { private readonly IMyRepository myRepository; public MyService(IMyRepository myRepository) { this.myRepository = myRepository; } [WebRouter("/", HttpMethod.Post)] public async Task Hello(MyInput input) { var result = new MyOutput() { Words = $"hello {input.Name ?? "nobody"}" }; await myRepository.SaveData(result); return await Task.FromResult(result); } } public class MyRepository : IMyRepository { public async Task SaveData(MyOutput data) { Console.WriteLine($"保存成功:{data.Words}"); return await Task.FromResult(true); } }

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

public abstract class DynamicPorxy { public abstract Delegate Instance { get; set; } } public class DynamicPorxyImpl : DynamicPorxy where Timpl : class where Tinput : class where Toutput : class { public override Delegate Instance { get; set; } public DynamicPorxyImpl(MethodInfo method) { Instance = ([FromServices] IServiceProvider sp, Tinput input) => ExpressionTool.CreateMethodDelegate(method)(sp.GetService(typeof(Tsvc)) as Timpl, input); } } public class DynamicPorxyImpl : DynamicPorxy where Timpl : class where Toutput : class { public override Delegate Instance { get; set; } public DynamicPorxyImpl(MethodInfo method) { Instance = ([FromServices] IServiceProvider sp) => ExpressionTool.CreateMethodDelegate(method)(sp.GetService(typeof(Tsvc)) as Timpl); } }

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

public class DynamicPorxyFactory { public static 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), new object[] { methodinfo }) as DynamicPorxy; else dynamicPorxy = Activator.CreateInstance(typeof(DynamicPorxyImpl<,,>).MakeGenericType(methodinfo.DeclaringType.GetInterfaces()[0], methodinfo.DeclaringType, methodinfo.ReturnType), new object[] { methodinfo }) as DynamicPorxy; yield return (webRouter, dynamicPorxy); } } }

internal class ExpressionTool { internal static Func CreateMethodDelegate(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>(reExpression, mParameter, pParameter).Compile(); } internal static Func CreateMethodDelegate(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>(reExpression, mParameter).Compile(); } }

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

public static class WebApplicationBuilderExtension { static Func 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 }; public static WebApplication RegisterDependencyAndMapDelegate(this WebApplicationBuilder webApplicationBuilder, Action registerDependencyAction, Func> 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 class MyServiceDependency { public static void Register(IServiceCollection services) { services.AddScoped(); services.AddScoped(); } }

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

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

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

到此这篇关于使用.Net6中的WebApplication打造最小API的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java使用JavaMail API发送和接收邮件的代码示例(java使用什么关键字定义类)
下一篇:PHP开发api接口安全验证操作实例详解(php api接口安全设计)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~