Ejemplo n.º 1
0
        /// <summary>
        /// Prepares Autofac container builder with common services.
        /// </summary>
        /// <returns>Autofac container builder.</returns>
        public static ContainerBuilder CreateBuilder()
        {
            var builder = new ContainerBuilder();

            // Bindings.
            builder.RegisterType <AutofacServiceProvider>().As <IServiceProvider>().InstancePerRequest()
            .InstancePerLifetimeScope();
            builder.RegisterType <DataAccess.AppDbContext>().AsSelf();
            builder.RegisterType <DataAccess.AppUnitOfWorkFactory>().AsSelf().AsImplementedInterfaces();
            builder.Register(c => c.Resolve <DataAccess.AppUnitOfWorkFactory>().Create()).AsImplementedInterfaces();
            builder.RegisterType <Domain.Users.Queries.UserQueries>().AsSelf();
            builder.RegisterType <Domain.Products.Queries.ProductQueries>().AsSelf();
            builder.RegisterType <Domain.Products.Queries.CompanyQueries>().AsSelf();

            // Repository for messages.
            var connectionString           = ConfigurationManager.ConnectionStrings["AppDbContext"];
            var adoNetRepositoryMiddleware = new Tools.Messages.Common.PipelineMiddlewares.RepositoryMiddleware(
                new Tools.Messages.Common.Repositories.AdoNetMessageRepository(
                    System.Data.Common.DbProviderFactories.GetFactory(connectionString.ProviderName),
                    connectionString.ConnectionString,
                    Tools.Messages.Common.Repositories.AdoNetMessageRepository.Dialect.SqlServer
                    )
                );

            // Command pipeline.
            var messagePipelineContainer = new DefaultMessagePipelineContainer();

            messagePipelineContainer.AddCommandPipeline()
            .UseDefaultMiddlewares(System.Reflection.Assembly.GetAssembly(typeof(Domain.Users.Entities.User)))
            .AddMiddleware(adoNetRepositoryMiddleware);
            builder.RegisterInstance(messagePipelineContainer).As <IMessagePipelineContainer>().SingleInstance();
            builder.RegisterType <DefaultMessagePipelineService>().As <IMessagePipelineService>();

            return(builder);
        }
Ejemplo n.º 2
0
        public static IMessagePipelineContainer RegisterPipelines(params IMessagePipelineMiddleware[] middlewares)
        {
            var pipelinesContainer = new DefaultMessagePipelineContainer();

            // Repositories.
            var connectionStringConf = ConfigurationManager.ConnectionStrings["AppDbContext"];
            var connectionString     = connectionStringConf.ConnectionString.Replace("{baseUrl}",
                                                                                     AppDomain.CurrentDomain.BaseDirectory);
            var repositoryMiddleware = new Saritasa.Tools.Messages.Common.PipelineMiddlewares.RepositoryMiddleware(
                new Saritasa.Tools.Messages.Common.Repositories.AdoNetMessageRepository(
                    System.Data.Common.DbProviderFactories.GetFactory(connectionStringConf.ProviderName),
                    connectionString)
                );
            var recordRepositoryMiddleware = new Saritasa.Tools.Messages.Common.PipelineMiddlewares.RepositoryMiddleware(
                new Saritasa.Tools.Messages.Common.Repositories.WebServiceRepository()
                )
            {
                RethrowExceptions = false,
            };

            // Command.
            pipelinesContainer.AddCommandPipeline()
            .AddMiddleware(
                new Saritasa.Tools.Messages.Commands.PipelineMiddlewares.CommandHandlerLocatorMiddleware(
                    System.Reflection.Assembly.GetAssembly(typeof(Domain.UserContext.Entities.User))))
            .AddMiddleware(new Saritasa.Tools.Messages.Commands.PipelineMiddlewares.CommandHandlerResolverMiddleware())
            .AddMiddleware(new Saritasa.Tools.Messages.Commands.PipelineMiddlewares.CommandHandlerExecutorMiddleware
            {
                UseParametersResolve = true
            })
            .AddMiddleware(repositoryMiddleware)
            .AddMiddleware(recordRepositoryMiddleware);

            // Query.
            pipelinesContainer.AddQueryPipeline()
            .AddMiddleware(new Saritasa.Tools.Messages.Queries.PipelineMiddlewares.QueryObjectResolverMiddleware
            {
                UseInternalObjectResolver = true,
            })
            .AddMiddleware(new Saritasa.Tools.Messages.Queries.PipelineMiddlewares.QueryExecutorMiddleware())
            .AddMiddleware(repositoryMiddleware)
            .AddMiddleware(recordRepositoryMiddleware);

            // Event.
            pipelinesContainer.AddEventPipeline()
            .AddMiddleware(new Saritasa.Tools.Messages.Events.PipelineMiddlewares.EventHandlerLocatorMiddleware(
                               System.Reflection.Assembly.GetAssembly(typeof(Domain.UserContext.Entities.User))))
            .AddMiddleware(new Saritasa.Tools.Messages.Events.PipelineMiddlewares.EventHandlerExecutorMiddleware())
            .AddMiddleware(repositoryMiddleware)
            .AddMiddleware(recordRepositoryMiddleware);

            return(pipelinesContainer);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Configure services.
        /// </summary>
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <OMDbScrubberContext>(options => options.UseSqlServer(
                                                            configuration.GetConnectionString("DefaultConnection")));

            services.AddScoped <IMoviesService, EFCoreMoviesService>();

            var jsonFileMessageRepository = new JsonFileMessageRepository(Environment.CurrentDirectory + @"\Messages");
            var repositoryMiddleware      = new RepositoryMiddleware(jsonFileMessageRepository);

            var pipelineContainer = new DefaultMessagePipelineContainer();

            services.AddSingleton <IMessagePipelineContainer>(pipelineContainer);
            services.AddScoped <IMessagePipelineService, DefaultMessagePipelineService>();
            pipelineContainer.AddCommandPipeline().AddStandardMiddlewares(o => o.SetAssemblies(typeof(IMoviesService).Assembly)).AddMiddleware(repositoryMiddleware);
            pipelineContainer.AddQueryPipeline().AddStandardMiddlewares().AddMiddleware(repositoryMiddleware);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Configure services.
        /// </summary>
        /// <param name="services">Service collection.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // DB services.
            services.AddDbContext <EstateDbContext>(options => options.UseSqlServer(
                                                        Configuration.GetConnectionString("UnrealEstateDB")));

            // Generators services.
            services.AddScoped <ITokenGenerator, JwtTokenGenerator>();

            // Repositories services.
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <IListingRepository, ListingRepository>();
            services.AddScoped <ICommentRepository, CommentRepository>();

            // Pipeline services.
            var jsonFileMessageRepository = new JsonFileMessageRepository(Environment.CurrentDirectory + @"\Messages");
            var repositoryMiddleware      = new RepositoryMiddleware(jsonFileMessageRepository);

            var pipelineContainer = new DefaultMessagePipelineContainer();

            services.AddSingleton <IMessagePipelineContainer>(pipelineContainer);
            services.AddScoped <IMessagePipelineService, DefaultMessagePipelineService>();
            pipelineContainer.AddCommandPipeline()
            .AddStandardMiddlewares(o => o.SetAssemblies(typeof(IUserRepository).Assembly))
            .AddMiddleware(repositoryMiddleware);
            pipelineContainer.AddQueryPipeline().AddStandardMiddlewares().AddMiddleware(repositoryMiddleware);

            // Add Identity.
            services.AddIdentity <User, IdentityRole>(
                options =>
            {
                options.Password.RequiredLength         = 8;
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireUppercase       = true;
                options.Password.RequiredUniqueChars    = default;
                options.Password.RequireNonAlphanumeric = false;
            })
            .AddEntityFrameworkStores <EstateDbContext>()
            .AddDefaultUI()
            .AddDefaultTokenProviders();

            // Add authentication.
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata      = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer    = AuthOptions.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = AuthOptions.Audience,
                    ValidateLifetime = true,

                    IssuerSigningKey         = AuthOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true
                };
            });

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicyBuilder(JwtBearerDefaults.AuthenticationScheme)
                                        .RequireAuthenticatedUser()
                                        .Build();
            });

            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfiles(new List <Profile> {
                    new DtoMappingProfile(), new CommandMappingProfile()
                });
            });

            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            // Add swagger.
            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "Unreal Estate API",
                    TermsOfService = "None"
                });

                options.AddSecurityDefinition("Bearer", new ApiKeyScheme
                {
                    In          = "header",
                    Name        = "Authorization",
                    Description = "JWT Authorization header",
                    Type        = "apiKey"
                });

                options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> >
                {
                    { "Bearer", new string[] { } }
                });

                var xmlPath = Path.Combine(AppContext.BaseDirectory, $"{Assembly.GetExecutingAssembly().GetName().Name}.xml");
                options.IncludeXmlComments(xmlPath);
            });

            // Add MVC.
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }