最近与一些技术小伙伴的沟通中经常问我:微软.net6中的最小api是干什么用的?也不知道怎么用?他有什么优势?下面我会用几篇干货文章来实现最小api应用,希望能给带给小伙伴们收获。
问:.net最小api干什么用的?他有什么优势?
答:个人感觉其实用处不大,应该是微软对外的一个推广作用,显示.net6的强大,体现创建一个.net6项目只需要几个文件即可。(纯个人观点,如有误欢迎学习交流)
本文实战项目,相关代码可直接复用
github地址:https://github.com/hailang2ll/DMS.MPTEST
1
创建最小api项目
创建最小api项目比较简单,这是不具体说明,如图:
2
提前准备,模块注入
引用Autofac相关包文件
创建一个类名为AutofacModuleRegister,代码如下:
public class AutofacModuleRegister : Autofac.Module
{
public string RootPath { get; set; }
public List DllFiles { get; set; }
public AutofacModuleRegister(string rootPath, List dllFiles)
{
RootPath = rootPath;
DllFiles = dllFiles;
}
protected override void Load(ContainerBuilder builder)
{
foreach (var dllFile in DllFiles)
{
var basePath = AppContext.BaseDirectory;
#region 接口服务注入
var servicesDllFile = Path.Combine(RootPath, dllFile);
if (!(File.Exists(servicesDllFile)))
{
var msg = $"{servicesDllFile}未找到注入的服务文件";
throw new Exception(msg);
}
var assemblysServices = Assembly.LoadFrom(servicesDllFile);
builder.RegisterAssemblyTypes(assemblysServices)
.AsImplementedInterfaces()//表示注册的类型,以接口的方式注册不包括IDisposable接口
.InstancePerLifetimeScope()//即为每一个依赖或调用创建一个单一的共享的实例
.EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy,使用接口的拦截器,在使用特性 [Attribute] 注册时,注册拦截器可注册到接口(Interface)上或其实现类(Implement)上。使用注册到接口上方式,所有的实现类都能应用到拦截器。
.PropertiesAutowired();//开始属性注入
#endregion
}
}
}
3
依赖注入-接口定义
创建接口类名为IProductService,代码如下:
////// 产品接口 /// public interface IProductService { ////// /// ///Task GetProduct(long id); }
4
依赖注入-服务定义
创建服务类名为ProductService,代码如下:
////// 产品服务 /// public class ProductService : IProductService { ////// 获取产品信息 /// /// ///public async Task GetProduct(long id) { ProductEntityResult entity = new ProductEntityResult() { //long类型转为string输出 Id = "1125964271981826048", ProductName = "aaaa", ProductPrice = 125.23m, CreatedTime = DateTime.Now, }; return await Task.FromResult(entity); } }
4
依赖注入-控制器定义
创建控制器类名为InjectionController,代码如下:
////// autofac /// [Route("api/[controller]")] [ApiController] public class InjectionController : ControllerBase { ////// 构造函数注入 /// private readonly IProductService _productService; ////// 构造函数注入 /// public InjectionController(IProductService productService) { _productService = productService; } ////// 我是构造函数注入 /// /// ///[HttpGet("GetProduct")] public async Task GetProduct(long id) { return await _productService.GetProduct(id); } }
实战测试结果,调试如下图:
结果返回如下图:
以上实现了一个简单的最小api项目的依赖注入(构造函数注入),下一节实现属性构造注入。
本文实战项目,相关代码可直接复用
github地址:https://github.com/hailang2ll/DMS.MPTEST
相关推荐
.NET Core 小程序开发零基础系列(1)——开发者启用并牵手成功
.net core redis的全套操作
.NETCore 实现容器化Docker与私有镜像仓库管理
.netcore consul实现服务注册与发现(一)单机部署
.netcore consul实现服务注册与发现(二)集群完整版
点击【在看】与好朋友一起分享



