示例#1
0
 private static void RegisterTypes(IEnumerable <Assembly> assembliesToRegister, IServiceCollection services)
 {
     AssemblyScanner.FindValidatorsInAssemblies(assembliesToRegister).ForEach(pair =>
     {
         services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
     });
 }
        public DefaultValidatorProvider(IServiceProvider serviceProvider, IFairyBreadOptions options)
        {
            ServiceProvider = serviceProvider;

            var validatorResults = AssemblyScanner.FindValidatorsInAssemblies(options.AssembliesToScanForValidators).ToArray();

            if (!validatorResults.Any() && options.ThrowIfNoValidatorsFound)
            {
                throw new Exception($"No validators were found in the provided " +
                                    $"{nameof(IFairyBreadOptions)}.{nameof(IFairyBreadOptions.AssembliesToScanForValidators)} " +
                                    $"(with concrete type: {options.GetType().FullName}) which included: " +
                                    $"{string.Join(",", options.AssembliesToScanForValidators)}.");
            }

            foreach (var validatorResult in validatorResults)
            {
                var validatorType = validatorResult.ValidatorType;
                if (validatorType.IsAbstract)
                {
                    continue;
                }

                var validatedType = validatorResult.InterfaceType.GenericTypeArguments.Single();
                if (!Cache.TryGetValue(validatedType, out var validatorsForType))
                {
                    Cache[validatedType] = validatorsForType = new List <ValidatorDescriptor>();
                }

                var requiresOwnScope = ShouldBeResolvedInOwnScope(validatorType);

                var validatorDescriptor = new ValidatorDescriptor(validatorType, requiresOwnScope);

                validatorsForType.Add(validatorDescriptor);
            }
        }
示例#3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(builder => builder
#if DEBUG
                                .SetMinimumLevel(LogLevel.Trace)
#else
                                .SetMinimumLevel(LogLevel.Warning)
#endif
                                );

            TypeDescriptorProviderGenerator.AddTypeDescriptorProviders(typeof(Schema.Deployment).Namespace, typeof(SchemaExtentions.Deployment).Namespace);

            services.AddFileReaderService();

            services.AddBlazorFileSaver();

            services.AddSingleton <IState, State>();

            services.AddTransient <IValidatorFactory, ServiceProviderValidatorFactory>();

            var config = new FluentValidationMvcConfiguration();
            config.RegisterValidatorsFromAssemblyContaining <Startup>();

            AssemblyScanner.FindValidatorsInAssemblies(config.AssembliesToRegister).ForEach(pair => {
                services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
            });

            services.AddScoped <IAppInsights, AppInsights>();
        }
        /// <summary>
        ///     Adds validation
        /// </summary>
        /// <param name="services">The <see cref="IServiceCollection">services</see> is used to access the service collection</param>
        /// <param name="configuration">Application configuration object</param>
        /// <returns>The service collection</returns>
        public static IServiceCollection AddValidation(this IServiceCollection services, IConfiguration configuration)
        {
            var validators = AssemblyScanner.FindValidatorsInAssemblies(new[] { typeof(AssemblyAnchor).Assembly });

            validators.ForEach(validator => services.AddTransient(validator.InterfaceType, validator.ValidatorType));

            return(services);
        }
示例#5
0
        public static IServiceCollection AddValidations(this IServiceCollection services)
        {
            AssemblyScanner.FindValidatorsInAssemblies(assemblies).ForEach(f =>
            {
                services.AddTransient(f.InterfaceType, f.ValidatorType);
                services.AddTransient(f.ValidatorType, f.ValidatorType);
            });

            return(services);
        }
        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            var result = AssemblyScanner.
                         FindValidatorsInAssemblies(new[] { Assembly.GetExecutingAssembly() });

            foreach (var item in result)
            {
                kernel.Bind(item.InterfaceType).To(item.ValidatorType);
            }
        }
        public static IServiceCollection AddAppFluentValidation(this IServiceCollection services)
        {
            var assembliesToRegister = new[] { typeof(IAppDbContext).Assembly };

            AssemblyScanner.FindValidatorsInAssemblies(assembliesToRegister).ForEach(pair =>
            {
                services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
            });


            return(services);
        }
示例#8
0
        private static void RegisterValidatorService(IServiceCollection services)
        {
            var assembliesToRegister = new List <Assembly>()
            {
                typeof(LabelValidator).Assembly
            };

            AssemblyScanner.FindValidatorsInAssemblies(assembliesToRegister).ForEach(pair =>
            {
                services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
            });
        }
示例#9
0
        private void Populate()
        {
            foreach (var v in AssemblyScanner.FindValidatorsInAssemblies(AppDomain.CurrentDomain.GetAssemblies().Where(x => !x.IsDynamic)))
            {
                var genericArguments = v.ValidatorType.BaseType.GetGenericArguments();

                if (genericArguments.Length == 1)
                {
                    var targetType = genericArguments[0];
                    _validatorsByType[targetType] = v.ValidatorType;
                }
            }
        }
示例#10
0
        private static ServiceProvider SetupServiceProvider()
        {
            var services = new ServiceCollection();

            var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(p => !p.IsDynamic);

            AssemblyScanner
            .FindValidatorsInAssemblies(assemblies)
            .ForEach(result => services.AddScoped(result.InterfaceType, result.ValidatorType));

            services.AddMediatR(AppDomain.CurrentDomain.GetAssemblies(), null);
            services.AddScoped(typeof(IPipelineBehavior <,>), typeof(ValidatorPipelineBehavior <,>));

            return(services.BuildServiceProvider());
        }
示例#11
0
        /// <summary>
        /// Registers our pipeline system built with mediatr.
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblies">The list of <see cref="Assembly"/> to go through to list all available <see cref="AbstractValidator{T}"/>.</param>
        /// <returns></returns>
        public static IServiceCollection AddPipeline(
            this IServiceCollection services,
            params Assembly[] assemblies)
        {
            services.AddMediatR(assemblies);

            AssemblyScanner
            .FindValidatorsInAssemblies(assemblies)
            .ForEach(scan => services
                     .AddTransient(scan.InterfaceType, scan.ValidatorType)
                     .AddTransient(scan.ValidatorType, scan.ValidatorType));

            return(services
                   .AddTransient <IValidatorFactory, ServiceProviderValidatorFactory>()
                   .AddScoped(typeof(IPipelineBehavior <,>), typeof(ValidationBehavior <,>)));
        }
示例#12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            //FluenteValidation
            var assembliesToRegister = new List <Assembly>()
            {
                typeof(BaseContext).Assembly
            };

            AssemblyScanner.FindValidatorsInAssemblies(assembliesToRegister)
            .ForEach(pair =>
                     services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType))
                     );

            //AutoMapper
            Action <IMapperConfigurationExpression> autoMapperConfig = config =>
                                                                       config.ForAllMaps((type, map) =>
                                                                                         map.IgnoreAllPropertiesWithAnInaccessibleSetter(type)
                                                                                         );

            services.AddAutoMapper(autoMapperConfig, GetType().Assembly);

            //MediatR
            services.AddMediatR();
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(ValidationPipeline <,>));

            //Swagger
            services.AddSwaggerGen(ApiTitle, ApiVersions);

            //DbContext
            var assemblyName = GetType().Assembly.GetName().Name;
            Action <SqlServerDbContextOptionsBuilder> dbOptionsBuilder = options => {
                options.MigrationsAssembly(assemblyName);
                options.MaxBatchSize(100);
            };

            var commandConnectionString = Configuration.GetConnectionString("CommandConnectionString");
            var queryConnectionString   = Configuration.GetConnectionString("QueryConnectionString");

            Action <DbContextOptionsBuilder> commandDbOptions = options => options.UseSqlServer(commandConnectionString, dbOptionsBuilder);
            Action <DbContextOptionsBuilder> queryDbOptions   = options => options.UseSqlServer(queryConnectionString);

            services.AddDbContext <CommandContext>(commandDbOptions);
            services.AddDbContext <QueryContext>(queryDbOptions);
        }
示例#13
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            var assembliesToRegister = new List <Assembly>()
            {
                GetType().Assembly
            };

            AssemblyScanner.FindValidatorsInAssemblies(assembliesToRegister).ForEach(pair =>
            {
                services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
            });

            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            services.AddSingleton <ICezLog, LogNLog>();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1",
                             new OpenApiInfo
                {
                    Title          = "AddingStuffAndChecking",
                    Version        = "v1",
                    Description    = "An API to get students",
                    TermsOfService = new Uri("https://mojafirmalichydziwg.com/terms"),
                    Contact        = new OpenApiContact
                    {
                        Name  = "Cezary Walenciuk",
                        Email = "*****@*****.**",
                        Url   = new Uri("https://twitter.com/walenciukc"),
                    },
                    License = new OpenApiLicense
                    {
                        Name = "AddingStuffAndChecking API",
                        Url  = new Uri("https://mojafirmalichydziwg.com/license"),
                    },
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
                //c.SchemaFilter<AddFluentValidationRules>();
            });
        }
        public static IServiceCollection AddBusinessServices(this IServiceCollection services)
        {
            //setup fluent validation
            services.AddTransient <IValidatorFactory, ServiceProviderValidatorFactory>();
            var currentAssembly = typeof(Startup).GetTypeInfo().Assembly;

            AssemblyScanner.FindValidatorsInAssemblies(new Assembly[] { currentAssembly }).ForEach(pair => {
                services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
            });

            services.AddSingleton(typeof(IRepository <>), typeof(MemoryRepository <>));
            services.AddScoped <IProductService, ProductService>();
            services.AddScoped <IPromotionService, PromotionService>();
            services.AddScoped <IOrderCalculationWorkflowProcessor, OrderCalculationWorkflowProcessor>();
            services.AddScoped <IOrderService, OrderService>();

            return(services);
        }
        public static IServiceCollection AddApplication(this IServiceCollection services)
        {
            AssemblyScanner.FindValidatorsInAssemblies(new[] { Assembly.GetExecutingAssembly() })
            .ForEach(pair =>
            {
                services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType));
                services.Add(ServiceDescriptor.Transient(pair.ValidatorType, pair.ValidatorType));
            });

            services.AddAutoMapper(new[] { Assembly.GetExecutingAssembly() });

            services.AddMediatR(new[] { Assembly.GetExecutingAssembly() });

            services.RegisterPipelineBehaviors();

            services.RegisterServices();

            return(services);
        }
示例#16
0
        public static IServiceCollection AddMediatrPipeline(this IServiceCollection services)
        {
            services.AddMediatR(typeof(AssemblyAnchor));

            // Person of pipeline-behaviors is important
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(LoggingPipeline <,>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(SlowingPipeline <,>));
            services.AddTransient(typeof(IPipelineBehavior <,>), typeof(ValidationPipeline <,>));

            // Add validators
            var validators =
                AssemblyScanner.FindValidatorsInAssemblies(new[]
            {
                typeof(AssemblyAnchor).Assembly
            });

            validators.ForEach(validator =>
                               services.AddTransient(validator.InterfaceType,
                                                     validator.ValidatorType));

            return(services);
        }
示例#17
0
 private static void ValidationSetup(HttpConfiguration config, Container container)
 {
     FluentValidationModelValidatorProvider.Configure(config, provider => provider.ValidatorFactory = new SimpleInjectorFactory(container));
     AssemblyScanner.FindValidatorsInAssemblies(GetAssemblies()).ForEach(result =>
                                                                         container.Register(result.InterfaceType, result.ValidatorType));
 }