コード例 #1
0
    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);
    }
コード例 #2
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="builder"></param>
    /// <returns></returns>
    public static MicroserviceFrameworkBuilder UseAspNetCore(this MicroserviceFrameworkBuilder builder)
    {
        builder.Services.AddHttpContextAccessor();
        builder.Services.AddSingleton <IActionResultTypeMapper, ActionResultTypeMapper>();
        builder.Services.AddSingleton <IScopedServiceResolver, ScopedServiceResolver>();
        builder.Services.TryAddScoped <ISession, HttpSession>();

        builder.Services.AddSingleton(
            x => x.GetRequiredService <IOptions <JsonOptions> >().Value.JsonSerializerOptions);

        var jsonSerializerSettingsType = Type.GetType("Newtonsoft.Json.JsonSerializerSettings, Newtonsoft.Json");
        var jsonOptionsType            =
            Type.GetType(
                "Microsoft.AspNetCore.Mvc.MvcNewtonsoftJsonOptions, Microsoft.AspNetCore.Mvc.NewtonsoftJson");

        if (jsonSerializerSettingsType != null && jsonOptionsType != null)
        {
            builder.Services.AddSingleton(jsonSerializerSettingsType, (x) =>
            {
                var type = typeof(IOptions <>).MakeGenericType(jsonOptionsType);
                return(((dynamic)x.GetRequiredService(type)).Value.SerializerSettings);
            });
        }

        return(builder);
    }
コード例 #3
0
 public static MicroserviceFrameworkBuilder UseMySqlMigrator(this MicroserviceFrameworkBuilder builder, Type type,
                                                             string connectionString)
 {
     builder.Services.AddSingleton <InitializerBase>(provider => new MySqlMigrator(type, connectionString,
                                                                                   provider.GetRequiredService <ILogger <MySqlMigrator> >()));
     return(builder);
 }
コード例 #4
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="builder"></param>
    /// <returns></returns>
    public static MicroserviceFrameworkBuilder UseMediator(this MicroserviceFrameworkBuilder builder)
    {
        builder.Services.TryAddSingleton <IMediatorTypeMapper, MediatorTypeMapper>();
        builder.Services.TryAddScoped <IMediator, Mediator>();

        return(builder);
    }
コード例 #5
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="builder"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static MicroserviceFrameworkBuilder UseDefaultJsonHelper(this MicroserviceFrameworkBuilder builder,
                                                                    JsonSerializerOptions options = null)
    {
        Default.JsonHelper = options == null?JsonHelper.Create() : new JsonHelper(options);

        return(builder);
    }
コード例 #6
0
 public static MicroserviceFrameworkBuilder UseAutoMapper(this MicroserviceFrameworkBuilder builder,
                                                          params Assembly[] assemblies)
 {
     builder.Services.TryAddScoped <IObjectAssembler, AutoMapperObjectAssembler>();
     builder.Services.AddAutoMapper(assemblies);
     return(builder);
 }
コード例 #7
0
 public static MicroserviceFrameworkBuilder UseEventBus(this MicroserviceFrameworkBuilder builder)
 {
     builder.Services.TryAddSingleton <IEventBus, InProcessEventBus>();
     builder.Services.TryAddSingleton <IEventExecutor, DefaultEventExecutor>();
     builder.RegisterEventHandlers();
     return(builder);
 }
コード例 #8
0
    public static MicroserviceFrameworkBuilder UseEntityFramework(this MicroserviceFrameworkBuilder builder,
                                                                  Action <EntityFrameworkBuilder> configure)
    {
        var eBuilder = new EntityFrameworkBuilder(builder.Services);

        configure?.Invoke(eBuilder);
        builder.Services.UseEntityFramework();
        return(builder);
    }
コード例 #9
0
    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);
    }
コード例 #10
0
    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();
    }
コード例 #11
0
    public static MicroserviceFrameworkBuilder UseEventBusRabbitMQ(this MicroserviceFrameworkBuilder builder,
                                                                   IConfiguration configuration)
    {
        builder.RegisterEventHandlers();

        builder.Services.Configure <RabbitMQOptions>(configuration.GetSection("RabbitMQ"));
        builder.Services.AddSingleton <PersistentConnection>();
        builder.Services.AddSingleton <IEventExecutor, DefaultEventExecutor>();
        builder.Services.AddSingleton <IConnectionFactory>(provider =>
        {
            var opts = provider.GetRequiredService <IOptionsMonitor <RabbitMQOptions> >().CurrentValue;
            var connectionFactory = new ConnectionFactory
            {
                HostName = opts.HostName,
                DispatchConsumersAsync = true
            };
            if (opts.Port > 0)
            {
                connectionFactory.Port = opts.Port;
            }

            if (!string.IsNullOrWhiteSpace(opts.UserName))
            {
                connectionFactory.UserName = opts.UserName;
            }

            if (!string.IsNullOrWhiteSpace(opts.Password))
            {
                connectionFactory.Password = opts.Password;
            }

            return(connectionFactory);
        });
        builder.Services.AddSingleton <IEventBus>((services) =>
        {
            var connection    = services.GetRequiredService <PersistentConnection>();
            var eventExecutor = services.GetRequiredService <IEventExecutor>();
            var logger        = services.GetRequiredService <ILogger <EventBusRabbitMQ> >();
            var eventBus      = new EventBusRabbitMQ(services.GetRequiredService <IOptionsMonitor <RabbitMQOptions> >(),
                                                     connection, eventExecutor, logger);
            eventBus.SubscribeAllEventTypes();
            return(eventBus);
        });
        return(builder);
    }
コード例 #12
0
    /// <summary>
    ///
    /// </summary>
    /// <param name="builder"></param>
    /// <param name="settings"></param>
    /// <returns></returns>
    public static MicroserviceFrameworkBuilder UseNewtonsoftJsonHelper(this MicroserviceFrameworkBuilder builder,
                                                                       JsonSerializerSettings settings = null)
    {
        if (settings == null)
        {
            settings = new JsonSerializerSettings();
            settings.Converters.Add(new ObjectIdConverter());
            settings.Converters.Add(new EnumerationConverter());
            settings.ContractResolver = new CompositeContractResolver
            {
                new EnumerationContractResolver(),
                new CamelCasePropertyNamesContractResolver()
            };
        }

        JsonConvert.DefaultSettings = () => settings;
        Default.JsonHelper          = new NewtonsoftJsonHelper();

        return(builder);
    }
コード例 #13
0
 public static MicroserviceFrameworkBuilder UseAccessControl(this MicroserviceFrameworkBuilder builder,
                                                             IConfiguration configuration)
 {
     builder.Services.AddAccessControl(configuration);
     return(builder);
 }
コード例 #14
0
 public static MicroserviceFrameworkBuilder UseOptions(this MicroserviceFrameworkBuilder builder,
                                                       IConfiguration configuration)
 {
     builder.Services.AddOptions(configuration);
     return(builder);
 }
コード例 #15
0
 public static MicroserviceFrameworkBuilder UseAutoMapper(this MicroserviceFrameworkBuilder builder,
                                                          params Type[] types)
 {
     return(builder.UseAutoMapper(types.Select(x => x.Assembly).ToArray()));
 }
コード例 #16
0
 public static MicroserviceFrameworkBuilder UseAssemblyScanPrefix(this MicroserviceFrameworkBuilder builder,
                                                                  params string[] prefixes)
 {
     RuntimeUtilities.StartsWith.AddRange(prefixes);
     return(builder);
 }
コード例 #17
0
 /// <summary>
 /// 审计领域的模型(Type)在同个应用里面(即便是多 DbContext)也应该只配置在一个 DbContext 里面;
 /// 或者审计领域独享一个 DbContext
 /// </summary>
 /// <param name="builder"></param>
 /// <typeparam name="TAuditStore"></typeparam>
 /// <returns></returns>
 public static MicroserviceFrameworkBuilder UseAuditStore <TAuditStore>(this MicroserviceFrameworkBuilder builder)
     where TAuditStore : class, IAuditStore
 {
     builder.Services.AddScoped <IAuditStore, TAuditStore>();
     return(builder);
 }
コード例 #18
0
 public static MicroserviceFrameworkBuilder UseAuditStore(this MicroserviceFrameworkBuilder builder)
 {
     builder.UseAuditStore <LoggerAuditStore>();
     return(builder);
 }
コード例 #19
0
 public static MicroserviceFrameworkBuilder UseAutoMapper(this MicroserviceFrameworkBuilder builder)
 {
     return(builder.UseAutoMapper(RuntimeUtilities.GetAllAssemblies()));
 }