/// <summary>
/// 作用域批量注入grpc数据
/// </summary>
/// <typeparam name="IGrpcDependency">根据泛型获取需要注入的grpc接口</typeparam>
/// <param name="services"></param>
/// <returns></returns>
public static IServiceCollection AddGrpcScopedSerivce<IGrpcDependency>(this IServiceCollection services) where IGrpcDependency : class
{
var interfaceTypes = GetInterfaceTypes<IGrpcDependency>();
foreach (var implementType in interfaceTypes)
{
var grpcService = GetGrpcService(implementType, services);
services.AddScoped(implementType, g => grpcService);
}
return services;
}
/// <summary>
/// 获取需要注入的接口
/// </summary>
/// <typeparam name="IGrpcDependency"></typeparam>
/// <returns></returns>
private static Type[] GetInterfaceTypes<IGrpcDependency>()
{
var baseType = typeof(IGrpcDependency);
var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
var referencedAssemblies = System.IO.Directory.GetFiles(path, "*.dll").Select(Assembly.LoadFrom).ToArray();
var types = referencedAssemblies
.SelectMany(a => a.DefinedTypes)
.Select(type => type.AsType())
.Where(x => x != baseType && baseType.IsAssignableFrom(x)).ToArray();
var interfaceTypes = types.Where(x => x.IsInterface).ToArray();
return interfaceTypes;
}
/// <summary>
/// 获取grpc客户端服务
/// </summary>
/// <param name="t"></param>
/// <param name="config"></param>
/// <returns></returns>
private static object GetGrpcService(Type t, IServiceCollection services)
{
var channel = GetGrpcChannel(services);
//由于是扩展方法,所以不能通过反射 GrpcChannel 调用,需要使用扩展类 GrpcClientFactory 调用
var grpcClientFactory = typeof(GrpcClientFactory);
//筛选指定方法
var grpcService = grpcClientFactory.GetMethods().Where(m =>
m.Name == "CreateGrpcService" &&
m.GetParameters().Length > 1 &&
m.GetParameters()[0].ParameterType == typeof(ChannelBase) &&
m.GetParameters()[1].ParameterType == typeof(ClientFactory)
).FirstOrDefault();
//MakeGenericMethod 将泛型传递给泛型方法<>,
return grpcService.MakeGenericMethod(t).Invoke(null, new object[] { channel, null });
}