.net core 的处理流程是一个管道,根据注册的中间件的顺序来处理请求及相应,相应的,在微服务的架构中,由于项目拆分,导致出现几十或者数百的子项目,但是某些中间件的调用却是一致的,所以写成公共调用中间件的方法必不可少。将服务的注册利用反射实现自动注入:如下代码,写公共方法实现服务注册及公用中间件注册
新建类 ServiceCollectionRegister
/// <summary>
/// 注入调用
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection Configure(this IServiceCollection services)
{
//MvcServiceCollectionExtensions.AddControllers(services);
services.AddControllers();
BatchInjection(services);
SwaggerInjection(services);
return services;
}
/// <summary>
/// 批量注入--服务自动注入
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection BatchInjection(this IServiceCollection services)
{
//读配置文件获取service程序集名称
var serviceAssembly = Utls.GetSectionValue("ServiceAssembly");
Assembly assembly = Assembly.Load(serviceAssembly);
//获取程序集下所有类
Type[] types = assembly.GetTypes();
types.ToList().ForEach(t =>
{
//非接口,非抽象类
if(!t.IsInterface && !t.IsAbstract)
{
Type[] interfaces = t.GetInterfaces();
//注入
interfaces.ToList().ForEach(r =>
{
//ServiceCollectionServiceExtensions.AddTransient(services, r, t);
services.AddTransient(r, t);
});
}
});
return services;
}
/// <summary>
/// 注入swagger
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection SwaggerInjection(this IServiceCollection services)
{
//参数可读配置
services.AddSwaggerGen(t =>
{
t.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1", Description = "仅作为实现插件注入功能" });
});
return services;
}
新建类 ServiceCollectionBuilder.cs ,里面实现对中间件的启动
/// <summary>
/// 注入调用
/// </summary>
/// <param name="services"></param>
/// <returns></returns>
public static IApplicationBuilder Configure(this IApplicationBuilder app, IHostApplicationLifetime lifetime)
{
//app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
RegisterSwagger(app);
return app;
}
/// <summary>
/// swagger中间件注册
/// </summary>
/// <param name="app"></param>
/// <returns></returns>
public static IApplicationBuilder RegisterSwagger(this IApplicationBuilder app)
{
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "测试注入");
//c.RoutePrefix = string.Empty; 设置这个将不显示swaggerui
c.RoutePrefix = "swagger";
});
return app;
}
在Startup中调用:
public void ConfigureServices(IServiceCollection services)
{
ServiceCollectionRegister.Configure(services);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime lifetime)
{
ServiceCollectionBuilder.Configure(app, lifetime);
}
其中重要的实现是通过反射实现服务的注册,而不需要新增一个服务还要去Configure中写服务注册。
附上项目代码地址:
Github代码地址