public static MicroserviceFrameworkBuilder RegisterEventHandlers(this MicroserviceFrameworkBuilder builder) { MicroserviceFrameworkLoaderContext.Get(builder.Services).ResolveType += type => { var interfaces = type.GetInterfaces(); var handlerInterfaceTypes = interfaces .Where(@interface => @interface.IsGenericType && EventHandlerBaseType == @interface.GetGenericTypeDefinition()) .ToList(); if (handlerInterfaceTypes.Count == 0) { return; } foreach (var handlerInterfaceType in handlerInterfaceTypes) { var eventType = handlerInterfaceType.GenericTypeArguments[0]; if (!eventType.IsEvent()) { throw new MicroserviceFrameworkException($"{eventType} 不是合法的事件类型"); } // 消息队列,得知道系统实现了哪些 EventHandler 才去监听对应的 Topic,所以必须先注册监听。 EventSubscriptionManager.Register(eventType, handlerInterfaceType); // 每次收到的消息都是独立的 Scope ServiceCollectionUtilities.TryAdd(builder.Services, new ServiceDescriptor(handlerInterfaceType, type, ServiceLifetime.Scoped)); } }; return(builder); }
public static void AddMicroserviceFramework(this IServiceCollection services, Action <MicroserviceFrameworkBuilder> builderAction = null) { var builder = new MicroserviceFrameworkBuilder(services); builder.Services.TryAddSingleton <ApplicationInfo>(); builder.UseDefaultJsonHelper(); // 放到后面,加载优先级更高 builderAction?.Invoke(builder); // 请保证这在最后,不然类型扫描事件的注册会晚于扫描 MicroserviceFrameworkLoaderContext.Get(services).LoadTypes(); }
public static MicroserviceFrameworkBuilder UseDependencyInjectionLoader( this MicroserviceFrameworkBuilder builder) { MicroserviceFrameworkLoaderContext.Get(builder.Services).ResolveType += type => { var lifetime = LifetimeUtilities.GetLifetime(type); if (lifetime.HasValue) { builder.Services.RegisterDependencyInjection(type, lifetime.Value); } }; return(builder); }
public static IServiceCollection AddOptions(this IServiceCollection services, IConfiguration configuration) { services.AddOptions(); MicroserviceFrameworkLoaderContext.Get(services).ResolveType += type => { if (type.IsAbstract || type.IsInterface) { return; } var attribute = type.GetCustomAttribute <OptionsTypeAttribute>(); if (attribute != null) { var section = string.IsNullOrWhiteSpace(attribute.Section) ? configuration : configuration.GetSection(attribute.Section); services.AddOptions(type, section, _ => { }); } }; return(services); }