コード例 #1
0
ファイル: Startup.cs プロジェクト: wladioh/cqrs-es
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();

            services.AddSingleton <IMapper, MapperService>();

            services.Scan(scan => scan
                          .FromAssemblyOf <EmployeeRepository>()
                          .AddClasses(classes => classes.AssignableTo(typeof(IBaseRepository <>)))
                          .AsImplementedInterfaces()
                          .WithScopedLifetime());

            services.AddSingleton(new Router());
            services.AddSingleton <ICommandSender>(y => y.GetService <Router>());
            services.AddSingleton <IEventPublisher>(y => y.GetService <Router>());
            services.AddSingleton <IHandlerRegistrar>(y => y.GetService <Router>());
            services.AddSingleton <IQueryProcessor>(y => y.GetService <Router>());
            services.AddSingleton <IEventStore, Infra.EventStore>();
            services.AddSingleton <ICache, MemoryCache>();
            services.AddScoped <IRepository>(y => new CacheRepository(new Repository(y.GetService <IEventStore>()), y.GetService <IEventStore>(), y.GetService <ICache>()));

            services.AddScoped <ISession, Session>();
            services.Scan(scan => scan
                          .FromAssemblies(typeof(EmployeeEventHandler).GetTypeInfo().Assembly)
                          .AddClasses(classes => classes.Where(x =>
            {
                var allInterfaces = x.GetInterfaces();
                return
                (allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IQueryHandler <,>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableQueryHandler <,>)));
            }))
                          .AsSelf()
                          .WithTransientLifetime()
                          );
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddFluentValidation(a => a.RegisterValidatorsFromAssemblyContaining <Startup>());
            services.AddSingleton <IConnectionMultiplexer>(s => ConnectionMultiplexer.Connect(Configuration["Redis"]));
            services.AddSingleton(s => EventStoreConnection.Create(Configuration["EventStore"]));
            var serviceProvider = services.BuildServiceProvider();
            var registrar       = new RouteRegistrar(new Provider(serviceProvider));

            registrar.RegisterInAssemblyOf(typeof(EmployeeEventHandler));
            TypeAdapterConfig.GlobalSettings.Scan(GetType().Assembly);
            return(serviceProvider);
        }
コード例 #2
0
ファイル: Startup.cs プロジェクト: zatona/CQRSlite
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMemoryCache();

            //Add Cqrs services
            services.AddSingleton <Router>(new Router());
            services.AddSingleton <ICommandSender>(y => y.GetService <Router>());
            services.AddSingleton <IEventPublisher>(y => y.GetService <Router>());
            services.AddSingleton <IHandlerRegistrar>(y => y.GetService <Router>());
            services.AddSingleton <IQueryProcessor>(y => y.GetService <Router>());
            services.AddSingleton <IEventStore, InMemoryEventStore>();
            services.AddSingleton <ICache, MemoryCache>();
            services.AddScoped <IRepository>(y => new CacheRepository(new Repository(y.GetService <IEventStore>()), y.GetService <IEventStore>(), y.GetService <ICache>()));
            services.AddScoped <ISession, Session>();

            //Scan for commandhandlers and eventhandlers
            services.Scan(scan => scan
                          .FromAssemblies(typeof(InventoryCommandHandlers).GetTypeInfo().Assembly)
                          .AddClasses(classes => classes.Where(x => {
                var allInterfaces = x.GetInterfaces();
                return
                (allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IQueryHandler <,>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableQueryHandler <,>)));
            }))
                          .AsSelf()
                          .WithTransientLifetime()
                          );
            // Add framework services.
            services.AddMvc();

            //Register routes
            services.AddHttpContextAccessor(); // No longer registered by default in ASP.NET Core 2.1
            var serviceProvider = services.BuildServiceProvider();
            var registrar       = new RouteRegistrar(new Provider(serviceProvider));

            registrar.RegisterInAssemblyOf(typeof(InventoryCommandHandlers));

            return(serviceProvider);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: shbszxj/demo
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType <CustomMessageBus>().SingleInstance();
            builder.Register(c => c.Resolve <CustomMessageBus>()).As <ICommandSender>();
            builder.Register(c => c.Resolve <CustomMessageBus>()).As <IEventPublisher>();
            builder.Register(c => c.Resolve <CustomMessageBus>()).As <IHandlerRegistrar>();

            builder.RegisterType <Notifier>().SingleInstance();

            builder.RegisterType <TestService>().As <ITestService>().SingleInstance();
            builder.RegisterType <NotificationService>().SingleInstance();

            using (var container = builder.Build())
            {
                var bus = new RouteRegistrar(new DependencyResolver(container));

                var types = typeof(CustomMessageBus).Assembly.GetExportedTypes()
                            .Where(type => type.GetInterfaces().Contains(typeof(IHandlerRegistrar)));

                bus.RegisterInAssemblyOf(types.ToArray());

                HostService <ITestService>(container, "TestService");

                //HostNotificationService(container, "NotificationService");

                HostNotificationServiceViaNetTcp(container, "NotificationService");

                System.Console.WriteLine("Press <Enter> to stop the service.");
                System.Console.ReadLine();

                foreach (var host in Hosts)
                {
                    host.Close();
                }
                Environment.Exit(0);
            }
        }
コード例 #4
0
        static async Task Main(string[] args)
        {
            var services = new ServiceCollection();

            services.AddMemoryCache();

            // CQRSLite

            services.AddSingleton(new Router());

            services.AddSingleton <ICommandSender>(y => y.GetService <Router>());
            services.AddSingleton <IEventPublisher>(y => y.GetService <Router>());
            services.AddSingleton <IHandlerRegistrar>(y => y.GetService <Router>());
            services.AddSingleton <IQueryProcessor>(y => y.GetService <Router>());

            services.AddSingleton <IEventStore, InMemoryEventStore>();

            services.AddSingleton <ICache, MemoryCache>();

            services.AddScoped <IRepository>(y => new CacheRepository(new Repository(y.GetService <IEventStore>()), y.GetService <IEventStore>(), y.GetService <ICache>()));

            services.AddScoped <ISession, Session>();

            // Scan for CommandHandlers and EventHandlers

            services.Scan(scan => scan
                          .FromAssemblies(typeof(Program).GetTypeInfo().Assembly)
                          .AddClasses(classes => classes.Where(x =>
            {
                var allInterfaces = x.GetInterfaces();
                return
                (allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IQueryHandler <,>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableQueryHandler <,>)));
            }))
                          .AsSelf()
                          .WithTransientLifetime());

            var provider = services.BuildServiceProvider();

            var registrar = new RouteRegistrar(provider);


            registrar.RegisterInAssemblyOf(typeof(Program));

            //
            // Execute

            var commandSender  = provider.GetRequiredService <ICommandSender>();
            var queryProcessor = provider.GetRequiredService <IQueryProcessor>();

            //

            var aggregateId = Guid.NewGuid();

            var createTopicCommand = new CreateTopicCommand(aggregateId, "Hello World!", "This is the initial post");

            await commandSender.Send(createTopicCommand);

            // Get the read model

            var data = await queryProcessor.Query(new GetTopicByIdQuery(aggregateId));

            Console.WriteLine(JsonSerializer.Serialize(data));

            //

            var       tasks = new List <Task>();
            const int limit = 499;

            for (var i = 0; i < limit; i++)
            {
                var replyToTopicCommand = new ReplyToTopicCommand(aggregateId, $"This is a reply #{i}", DateTime.UtcNow.AddDays(limit * -1 + i), data.Version);

                tasks.Add(commandSender.Send(replyToTopicCommand));
            }

            await Task.WhenAll(tasks);

            //

            data = await queryProcessor.Query(new GetTopicByIdQuery(aggregateId));

            Console.WriteLine(JsonSerializer.Serialize(data));

            Console.WriteLine("DONE!");
            Console.ReadKey();
        }
コード例 #5
0
        /// <summary>
        /// Configures the services.
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">Services.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHttpContextAccessor();

            services.AddMemoryCache();

            //Add Cqrs services
            services.AddSingleton <Router>(new Router());
            services.AddSingleton <ICommandSender>(y => y.GetService <Router>());
            services.AddSingleton <IEventPublisher>(y => y.GetService <Router>());
            services.AddSingleton <IHandlerRegistrar>(y => y.GetService <Router>());
            services.AddScoped <IEventStore, SqliteEventStore>();
            services.AddSingleton <ICache, MemoryCache>();
            services.AddScoped <IRepository>(y => new CacheRepository(new Repository(y.GetService <IEventStore>()), y.GetService <IEventStore>(), y.GetService <ICache>()));
            services.AddScoped <CQRSlite.Domain.ISession, Session>();

            services.AddDbContext <DatabaseContext>(options => options.UseSqlite("Data Source=CQRSGame.db"));

            services.AddTransient <IDatabaseService>(sp => new DatabaseService(sp.GetRequiredService <DatabaseContext>()));
            services.AddTransient <IGameQueries, GameQueries>();

            //Scan for commandhandlers and eventhandlers
            services.Scan(scan => scan
                          .FromAssemblies(typeof(GameCommandHandlers).GetTypeInfo().Assembly)
                          .AddClasses(classes => classes.Where(x =>
            {
                var allInterfaces = x.GetInterfaces();
                return
                (allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableHandler <>)));
            }))
                          .AsSelf()
                          .WithTransientLifetime()
                          );

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo
                {
                    Version     = "v1",
                    Title       = "RTTicTacToe - API",
                    Description = "ASP.NET Core Web API with the implementation of the RTTicTacToe game backend",
                    Contact     = new OpenApiContact
                    {
                        Name  = "José Pereira",
                        Email = "*****@*****.**",
                        Url   = new Uri("https://twitter.com/z_leao")
                    }
                });

                // Set the comments path for the Swagger JSON and UI.
                var xmlPath = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
                c.IncludeXmlComments(xmlPath);
            });

            //Register routes
            var serviceProvider = services.BuildServiceProvider();
            var registrar       = new RouteRegistrar(new Provider(serviceProvider));

            registrar.RegisterInAssemblyOf(typeof(GameCommandHandlers));

            //Add support for SignalR
            services.AddSignalR();

            // Configure controllers behaviour
            services.AddControllers();
        }
コード例 #6
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            // App Settings
            services.Configure <RavenSettings>(Configuration.GetSection("Raven"));

            services.AddMemoryCache();

            // Auto Mapper Extensions DI.
            services.AddAutoMapper();

            // Add cqrs services
            services.AddRaven();

            services.AddSingleton(new Router());
            services.AddSingleton <ICommandSender>(y => y.GetService <Router>());
            services.AddSingleton <IEventPublisher>(y => y.GetService <Router>());
            services.AddSingleton <IHandlerRegistrar>(y => y.GetService <Router>());
            services.AddSingleton <IEventStore, RavenDBEventStore>();
            //services.AddSingleton<IEventStore, InMemoryEventStore>();
            services.AddSingleton <ICache, MemoryCache>();
            services.AddScoped <IRepository>(y => new CacheRepository(new Repository(y.GetService <IEventStore>()), y.GetService <IEventStore>(), y.GetService <ICache>()));
            services.AddScoped <ISession, Session>();



            // Redis Setting
            //var redisConfig = Configuration.Get<RedisConfiguration>();
            var multiplexer = ConnectionMultiplexer.Connect(Configuration.GetSection("Redis").GetValue <string>("ConnectionString"));

            services.AddSingleton <IConnectionMultiplexer>(multiplexer);

            // Use Scrutor extensions to scan assemblies.
            services.Scan(scan =>
            {
                scan.FromAssemblyOf <ILocationRepository>()
                .AddClasses(classes => classes.Where(x =>
                {
                    var allInterfaces = x.GetInterfaces();
                    return(allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IBaseRepository <>)));
                }))
                .AsImplementedInterfaces()
                .WithTransientLifetime();

                scan.FromAssemblyOf <LocationCommandHandler>()
                .AddClasses(classes => classes.Where(x =>
                {
                    var allInterfaces = x.GetInterfaces();
                    return(allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IHandler <>)) ||
                           allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableHandler <>)));
                }))
                .AsSelf()
                .WithTransientLifetime();
            });

            // Add framework services.
            services.AddMvc(config =>
            {
                config.Filters.Add(new BadRequestActionFilter());
            })
            .AddFluentValidation(fv =>
                                 fv.RegisterValidatorsFromAssemblyContaining <CreateEmployeeRequestValidator>()
                                 );

            // Register routes.
            var serviceProvider = services.BuildServiceProvider();
            var registrar       = new RouteRegistrar(serviceProvider);

            registrar.RegisterInAssemblyOf(typeof(LocationCommandHandler));

            return(serviceProvider);
        }
コード例 #7
0
ファイル: Startup.cs プロジェクト: jshuckeba/netcore_cqrs
        /// <summary>
        /// Configures the services. This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">The services.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // Elasticsearch
            services.AddSingleton <IConnectionPool, SingleNodeConnectionPool>(s =>
            {
                var elasticSearchSettings = s.GetService <IOptions <ElasticSearchSettings> >();
                return(new SingleNodeConnectionPool(new Uri(elasticSearchSettings.Value.ElasticUrl)));
            });

            services.AddSingleton <IConnectionSettingsValues, ConnectionSettings>(
                s => new ConnectionSettings(s.GetService <IConnectionPool>())
                .ThrowExceptions());

            services.AddTransient <IElasticClient, ElasticClient>(s =>
            {
                var settings = (IConnectionSettingsValues)s.GetService(typeof(IConnectionSettingsValues));
                return(new ElasticClient(settings));
            });

            // CQRS
            services.AddSingleton(new Router());
            services.AddSingleton <ICommandSender>(y => y.GetService <Router>());
            services.AddSingleton <IEventPublisher>(y => y.GetService <Router>());
            services.AddSingleton <IHandlerRegistrar>(y => y.GetService <Router>());
            services.AddTransient <IEventStore, ElasticEventStore>();
            services.AddSingleton <ICache, MemoryCache>();
            services.AddScoped <IRepository>(y => new CacheRepository(new Repository(y.GetService <IEventStore>()), y.GetService <IEventStore>(), y.GetService <ICache>()));
            services.AddScoped <ISession, Session>();
            services
            .AddTransient <IReadModelRepository <InventoryItemDetailsDto, Guid>,
                           ElasticRepository <InventoryItemDetailsDto, Guid> >();
            services
            .AddTransient <IReadModelRepository <InventoryItemListDto, Guid>,
                           ElasticRepository <InventoryItemListDto, Guid> >();
            services.AddTransient <IReadModelFacade, ReadModelFacade>();

            //Scan for commandhandlers
            services.Scan(scan => scan
                          .FromAssemblies(typeof(InventoryCommandHandlers).GetTypeInfo().Assembly)
                          .AddClasses(classes => classes.Where(x => {
                var allInterfaces = x.GetInterfaces();
                return
                (allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IHandler <>)) ||
                 allInterfaces.Any(y => y.GetTypeInfo().IsGenericType&& y.GetTypeInfo().GetGenericTypeDefinition() == typeof(ICancellableHandler <>)));
            }))
                          .AsSelf()
                          .WithTransientLifetime()
                          );

            // Register routes
            var serviceProvider = services.BuildServiceProvider();
            var registrar       = new RouteRegistrar(new ScopedServiceProvider(serviceProvider));

            registrar.RegisterInAssemblyOf(typeof(InventoryCommandHandlers));

            // Configure CORS
            services.AddCors(
                options =>
            {
                options.AddPolicy(
                    "ConfiguredCorsPolicy",
                    builder =>
                {
                    var allowedOrigins = (Configuration["Cors:Origins"] ?? string.Empty).Split(',')
                                         .Select(x => x.Trim())
                                         .Where(x => !string.IsNullOrWhiteSpace(x))
                                         .ToArray();
                    var allowedMethods = (Configuration["Cors:Methods"] ?? string.Empty).Split(',')
                                         .Select(x => x.Trim())
                                         .Where(x => !string.IsNullOrWhiteSpace(x))
                                         .ToArray();
                    var allowedHeaders = (Configuration["Cors:Headers"] ?? string.Empty).Split(',')
                                         .Select(x => x.Trim())
                                         .Where(x => !string.IsNullOrWhiteSpace(x))
                                         .ToArray();

                    var b = allowedOrigins.Length == 0 ? builder.AllowAnyOrigin() : builder.WithOrigins(allowedOrigins);

                    b = allowedMethods.Length == 0 ? b.AllowAnyMethod() : b.WithMethods(allowedMethods);

                    if (allowedHeaders.Length == 0)
                    {
                        b.AllowAnyHeader();
                    }
                    else
                    {
                        b.WithHeaders(allowedHeaders);
                    }
                });
            });

            services.Configure <MvcOptions>(options => { options.Filters.Add(new CorsAuthorizationFilterFactory("ConfiguredCorsPolicy")); });

            // Compression
            services.Configure <GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);
            services.AddResponseCompression();

            // SignalR
            services.AddSignalR();
            services.AddSingleton <InventoryHub, InventoryHub>();

            // Services
            services.AddSingleton <IOrderService, PretendOrderService>();

            // Swagger
            services.AddSwaggerGen(
                options =>
            {
                options.SwaggerDoc("v1", new Info {
                    Title = "netcore_CQRS", Version = "v1"
                });

                var xmlPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "InventoryApi.xml");
                options.IncludeXmlComments(xmlPath);
            });
        }
コード例 #8
0
        public async Task DoStuff()
        {
            var watch = new Stopwatch();

            watch.Start();
            var         router     = new Router();
            var         eventstore = new EventStore(router);
            IRepository rep        = new Repository(eventstore);
            var         cache      = new MemoryCache();
            //rep = new CacheRepository(rep, eventstore, cache);
            var session = new Session(rep);

            for (var index = 0; index < 15_000; index++)
            {
                await session.Add(new Employee(Guid.NewGuid()));
            }
            await session.Commit();

            for (var i = 0; i < 15_000; i++)
            {
                await session.Add(new Employee(Guid.NewGuid()));

                await session.Commit();
            }

            for (var i = 0; i < 15_000; i++)
            {
                var rep2     = new Repository(eventstore);
                var session2 = new Session(rep2);
                await session2.Add(new Employee(Guid.NewGuid()));

                await session2.Commit();
            }

            Parallel.For(0, 300, async i =>
            {
                var id2      = Guid.NewGuid();
                var employee = new Employee(id2);
                var session2 = new Session(rep);

                await session2.Add(employee);
                await session2.Commit();

                for (int j = 0; j < 100; j++)
                {
                    var e = await session2.Get <Employee>(id2);
                    for (int k = 0; k < 10; k++)
                    {
                        e.GiveRaise(10);
                    }
                    await session2.Commit();
                }
            });



            var id = Guid.NewGuid();
            await session.Add(new Employee(id));

            await session.Commit();

            for (var i = 0; i < 5_000; i++)
            {
                var employee = await session.Get <Employee>(id);

                employee.GiveRaise(10);
                await session.Commit();
            }

            var registrar = new RouteRegistrar(new ServiceLocator(rep, router));

            registrar.RegisterInAssemblyOf(typeof(EmployeeGiveRaise));

            var num   = 3000;
            var tasks = new Task[num];

            for (int i = 0; i < num; i++)
            {
                tasks[i] = router.Send(new EmployeeGiveRaise(id, 10));
            }
            await Task.WhenAll(tasks);


            Parallel.For(0, 3000, async i =>
            {
                var id2      = Guid.NewGuid();
                var employee = new Employee(id2);
                var session2 = new Session(rep);

                await session2.Add(employee);
                await session2.Commit();

                for (int j = 0; j < 100; j++)
                {
                    await router.Send(new EmployeeGiveRaise(id2, 10));
                }
            });

            watch.Stop();
            Console.WriteLine($"{eventstore.Count:##,###} events saved");
            Console.WriteLine($"{eventstore.Read:##,###} events read from eventstore");
            Console.WriteLine($"{Employee.AppliedEvents:##,###} events applied");
            Console.WriteLine($"{watch.ElapsedMilliseconds:##,###} ms");
            Console.WriteLine($"{Employee.AppliedEvents / watch.ElapsedMilliseconds:##,###} events handled per ms");
        }