public static void AddKafkaConsumer(this ContainerBuilder builder, Action <SubscriberConfig> configurator) { Guard.NotNull(configurator, nameof(configurator)); var config = new SubscriberConfig(); // Consumer configurator(config); var events = config.EventAssemblies .SelectMany(a => a.GetTypes()) .Where(t => t.IsAssignableTo <Event>()); foreach (var type in events) { if (type.GetConstructors().Any(c => c.GetParameters().Count() == 0)) { var handlerType = typeof(IMessageHandler <>).MakeGenericType(type); var hasHandler = config .EventAssemblies .Any(ass => ass.GetTypes().Any(ty => handlerType.IsAssignableFrom(ty))); if (hasHandler) { config.Topics.Add(type.FullName); } } } builder.RegisterInstance(Options.Create(config)); builder.RegisterType <KafkaListenerService>() .As <IHostedService>() .InstancePerDependency(); builder .RegisterAssemblyTypes(config.EventAssemblies) .AsClosedTypesOf(typeof(IMessageHandler <>)) .AsImplementedInterfaces() .InstancePerDependency(); builder .RegisterType <HandlerInvoker>() .SingleInstance(); }
public KafkaListenerService( ILogger <KafkaListenerService> logger, HandlerInvoker handlerFactory, SubscriberConfig subscriberConfig) { if (!subscriberConfig.IsValid) { throw new ArgumentException(nameof(subscriberConfig)); } this._logger = logger; this._config = subscriberConfig; this._handlerFactory = handlerFactory; if (subscriberConfig.Topics == null || !subscriberConfig.Topics.Any()) { _logger.LogWarning("No topics found to subscribe"); } else { _logger.LogInformation($"subscribing to {JsonConvert.SerializeObject(subscriberConfig.Topics)}"); } }