Example #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogInformation("正在对服务进行配置...");

            services.AddMvc();

            var eventHandlerExecutionContext = new EventHandlerExecutionContext(services,
                                                                                sc => sc.BuildServiceProvider());

            services.AddSingleton <IEventHandlerExecutionContext>(eventHandlerExecutionContext);

            var connectionFactory = new ConnectionFactory {
                HostName = "localhost"
            };

            services.AddSingleton <IEventBus>(sp => new RabbitMQEventBus(connectionFactory,
                                                                         sp.GetRequiredService <ILogger <RabbitMQEventBus> >(),
                                                                         sp.GetRequiredService <IEventHandlerExecutionContext>(),
                                                                         RMQ_EXCHANGE,
                                                                         queueName: RMQ_QUEUE));

            var mongoServer   = Configuration["mongo:server"];
            var mongoDatabase = Configuration["mongo:database"];
            var mongoPort     = Convert.ToInt32(Configuration["mongo:port"]);

            services.AddSingleton <IDataAccessObject>(serviceProvider => new MongoDataAccessObject(mongoDatabase, mongoServer, mongoPort));

            this.logger.LogInformation("服务配置完成,已注册到IoC容器!");
        }
Example #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogInformation("正在对服务进行配置...");

            services.AddMvc();
            services.AddOptions();
            services.Configure <MssqlConfig>(Configuration.GetSection("mssql"));

            services.AddTransient <IEventStore>(serviceProvider =>
                                                new DapperEventStore(Configuration["mssql:connectionString"],
                                                                     serviceProvider.GetRequiredService <ILogger <DapperEventStore> >()));

            var eventHandlerExecutionContext = new EventHandlerExecutionContext(services,
                                                                                sc => sc.BuildServiceProvider());

            services.AddSingleton <IEventHandlerExecutionContext>(eventHandlerExecutionContext);
            // services.AddSingleton<IEventBus, PassThroughEventBus>();

            var connectionFactory = new ConnectionFactory {
                HostName = "localhost"
            };

            services.AddSingleton <IEventBus>(sp => new RabbitMQEventBus(connectionFactory,
                                                                         sp.GetRequiredService <ILogger <RabbitMQEventBus> >(),
                                                                         sp.GetRequiredService <IEventHandlerExecutionContext>(),
                                                                         RMQ_EXCHANGE,
                                                                         queueName: RMQ_QUEUE));

            this.logger.LogInformation("服务配置完成,已注册到IoC容器!");
        }
Example #3
0
 public override void Subscribe <TEvent, TEventHandler>()
 {
     if (!EventHandlerExecutionContext.IsHandlerRegistered <TEvent, TEventHandler>())
     {
         EventHandlerExecutionContext.RegisterHandler <TEvent, TEventHandler>();
     }
 }
Example #4
0
        /// <summary>
        /// 定义一个Queue, 以及事件接受所需的操作
        /// </summary>
        /// <param name="queue"></param>
        /// <returns></returns>
        private string InitializeQueue(string queue)
        {
            var localQueueName = queue;

            if (string.IsNullOrEmpty(localQueueName))
            {
                localQueueName = _channel.QueueDeclare().QueueName;
            }
            else
            {
                _channel.QueueDeclare(localQueueName, true, false, false, null);
            }

            var consumer = new EventingBasicConsumer(_channel);

            consumer.Received += async(model, eventArg) =>
            {
                var eventBody = eventArg.Body;
                var json      = Encoding.UTF8.GetString(eventBody);
                var @event    = (IEvent)JsonConvert.DeserializeObject(json,
                                                                      new JsonSerializerSettings {
                    TypeNameHandling = TypeNameHandling.All
                });
                await EventHandlerExecutionContext.HandleEventAsync(@event);

                if (!_autoAck)
                {
                    _channel.BasicAck(eventArg.DeliveryTag, false);
                }
            };
            _channel.BasicConsume(localQueueName, _autoAck, consumer);
            return(localQueueName);
        }
Example #5
0
        /// <summary>
        /// 添加事件组件
        /// </summary>
        /// <param name="services"></param>
        public static void AddDefaultEventBus(this IServiceCollection services)
        {
            var eventHandlerExecutionContext = new EventHandlerExecutionContext(services, sc => sc.BuildServiceProvider());

            services.AddSingleton <IEventHandlerExecutionContext>(eventHandlerExecutionContext);
            services.AddSingleton <IEventBus, PassThroughEventBus>();
        }
Example #6
0
 public override void Subscribe <TEvent, TEventHandler>()
 {
     if (!EventHandlerExecutionContext.IsHandlerRegistered <TEvent, TEventHandler>())
     {
         EventHandlerExecutionContext.RegisterHandler <TEvent, TEventHandler>();
         _channel.QueueBind(_queueName, _exchangeName, typeof(TEvent).FullName);
     }
 }
Example #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services.AddTransient <IEventStore>(serviceProvider =>
                                                new Infrastructure.EventStore.DapperEventStore(Configuration["mssql:connectionString"],
                                                                                               serviceProvider.GetRequiredService <ILogger <DapperEventStore> >()));

            var eventHandlerExecutionContext = new EventHandlerExecutionContext(services, sc => sc.BuildServiceProvider());

            services.AddSingleton <IEventHandlerExecutionContext>(eventHandlerExecutionContext);
        }
Example #8
0
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogInformation("正在对服务进行配置...");

            services.AddMvc();

            services.AddTransient <IEventStore>(serviceProvider =>
                                                new DapperEventStore(Configuration["mssql:connectionString"],
                                                                     serviceProvider.GetRequiredService <ILogger <DapperEventStore> >()));

            var eventHandlerExecutionContext = new EventHandlerExecutionContext(services,
                                                                                sc => sc.BuildServiceProvider());

            services.AddSingleton <IEventHandlerExecutionContext>(eventHandlerExecutionContext);
            services.AddSingleton <IEventBus, PassThroughEventBus>();

            this.logger.LogInformation("服务配置完成,已注册到IoC容器!");
        }
Example #9
0
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogInformation("正在对服务进行配置...");

            services.AddMvc();
            services.AddOptions();

            // Configure event store.
            services.Configure <PostgreSqlConfig>(Configuration.GetSection("postgresql"));
            services.AddTransient <IEventStore>(serviceProvider =>
                                                new DapperEventStore(Configuration["postgresql:connectionString"],
                                                                     serviceProvider.GetRequiredService <ILogger <DapperEventStore> >()));

            // Configure data access component.
            var mongoServer   = Configuration["mongo:server"];
            var mongoDatabase = Configuration["mongo:database"];
            var mongoPort     = Convert.ToInt32(Configuration["mongo:port"]);

            services.AddSingleton <IDataAccessObject>(serviceProvider => new MongoDataAccessObject(mongoDatabase, mongoServer, mongoPort));

            // Configure event handlers.
            var eventHandlerExecutionContext = new EventHandlerExecutionContext(services,
                                                                                sc => sc.BuildServiceProvider());

            services.AddSingleton <IEventHandlerExecutionContext>(eventHandlerExecutionContext);

            // Configure RabbitMQ.
            var connectionFactory = new ConnectionFactory {
                HostName = "localhost"
            };

            services.AddSingleton <IEventBus>(sp => new RabbitMQEventBus(connectionFactory,
                                                                         sp.GetRequiredService <ILogger <RabbitMQEventBus> >(),
                                                                         sp.GetRequiredService <IEventHandlerExecutionContext>(),
                                                                         RMQ_EXCHANGE,
                                                                         queueName: RMQ_QUEUE));

            this.logger.LogInformation("服务配置完成,已注册到IoC容器!");
        }
Example #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogInformation("正在对服务进行配置...");

            #region 跨域
            var isTrueStr  = configuration["HttpKYUrls:isTrue"];
            var httpUrlStr = configuration["HttpKYUrls:urlStr"];
            services.AddCors(options =>
            {
                options.AddPolicy("AllowSameDomainHttp", builder =>
                {
                    if (isTrueStr.Equals("true") && !string.IsNullOrWhiteSpace(httpUrlStr))
                    {
                        this.logger.LogInformation("注册跨域请求,指定路由为:" + httpUrlStr);
                        builder.WithOrigins(httpUrlStr.Split(','))
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();      //允许处理cookie
                    }
                    else
                    {
                        this.logger.LogInformation("注册跨域请求,允许所有主机访问");
                        builder.AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin() //允许所有来源的主机访问
                        .AllowCredentials();
                    }
                });
            });


            #endregion


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddOptions();
            services.Configure <WebApiConfig>(configuration.GetSection("WebApiConfig"));
            services.AddTransient <IEventStore>(serviceProvider =>
                                                new DapperEventStore(connStr,
                                                                     serviceProvider.GetRequiredService <ILogger <DapperEventStore> >()));

            var eventHandlerExecutionContext = new EventHandlerExecutionContext(services,
                                                                                sc => sc.BuildServiceProvider());
            services.AddSingleton <IEventHandlerExecutionContext>(eventHandlerExecutionContext);
            // services.AddSingleton<IEventBus, PassThroughEventBus>();
            services.AddDbContext <WebApiDbContext>(options => options.UseSqlServer(connStr));


            var connectionFactory = new ConnectionFactory {
                HostName = "localhost"
            };
            services.AddSingleton <IEventBus>(sp => new RabbitMQEventBus(connectionFactory,
                                                                         sp.GetRequiredService <ILogger <RabbitMQEventBus> >(),
                                                                         sp.GetRequiredService <IEventHandlerExecutionContext>(),
                                                                         RMQ_EXCHANGE,
                                                                         queueName: RMQ_QUEUE));

            #region 用户登录验证
            JWTTokenOptions jwtTokenOptions = new JWTTokenOptions(
                configuration["WebApiConfig:JWTIssuer"],
                configuration["WebApiConfig:JWTAudience"],
                configuration["WebApiConfig:JWTSecurityKey"],
                Convert.ToInt32(configuration["WebApiConfig:JWTExpires"])
                );

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                //认证失败,会自动跳转到这个地址
                options.LoginPath = "/Home/Login";
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = jwtTokenOptions.Key,

                    ValidateIssuer = true,
                    ValidIssuer    = jwtTokenOptions.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = jwtTokenOptions.Audience,

                    ValidateLifetime = true,
                    ClockSkew        = TimeSpan.FromMinutes(Convert.ToInt32(configuration["WebApiConfig:JWTClockSkew"]))
                };
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                //options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
            #endregion

            this.logger.LogInformation("服务配置完成,已注册到IoC容器!");
        }
Example #11
0
 private async void EventQueue_EventPushed(object sender, EventProcessedEventArgs e)
 {
     await EventHandlerExecutionContext.HandleEventAsync(e.Event);
 }