自学过程

关注公众号 jb51net

关闭
首页 > 网络编程 > ASP.NET > 自学过程 > .Net6打造最小API

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

作者:a1010

本文详细讲解了使用.Net6中的WebApplication打造最小API,文中通过示例代码介绍的非常详细。对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

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

环境准备

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

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

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

当然仅仅是这样,是无法用于生产的,毕竟不可能所有的业务单元我们塞进这么一个小小的表达式里。不过借助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<MyOutput> Hello(MyInput input);
    }
    public interface IMyRepository
    {
        Task<bool> SaveData(MyOutput data);
    }
    public class MyService : IMyService
    {
        private readonly IMyRepository myRepository;
        public MyService(IMyRepository myRepository)
        {
            this.myRepository = myRepository;
        }
        [WebRouter("/", HttpMethod.Post)]
        public async Task<MyOutput> 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<bool> 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<Tsvc, Timpl, Tinput, Toutput> : 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<Timpl, Tinput, Toutput>(method)(sp.GetService(typeof(Tsvc)) as Timpl, input);
        }
    }
    public class DynamicPorxyImpl<Tsvc, Timpl, Toutput> : DynamicPorxy where Timpl : class where Toutput : class
    {
        public override Delegate Instance { get; set; }
        public DynamicPorxyImpl(MethodInfo method)
        {
            Instance = ([FromServices] IServiceProvider sp) => ExpressionTool.CreateMethodDelegate<Timpl, Toutput>(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<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();
        }
        internal static 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容器:

public static class WebApplicationBuilderExtension
    {
        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
                };
        public static 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 class MyServiceDependency
    {
        public static void Register(IServiceCollection services)
        {
            services.AddScoped<IMyService, MyService>();
            services.AddScoped<IMyRepository, MyRepository>();
        }
    }

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

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

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

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

您可能感兴趣的文章:
阅读全文