private static void InitializeContainer(IInitializationExpression exp) { exp.For <IDbContextManager>() .Use <DbContextManager>(); exp.FillAllPropertiesOfType <IDbContextManager>() .Use <DbContextManager>(); exp.For(typeof(ISimpleRepository <>)) .Use(typeof(SimpleRepository <>)); exp.For <IAuthentication>() .Use <Authentication>(); exp.FillAllPropertiesOfType <IAuthentication>() .Use <Authentication>(); exp.Scan(cfg => { cfg.AssemblyContainingType <RepositoryBase>(); cfg.IncludeNamespaceContainingType <RepositoryBase>(); cfg.SingleImplementationsOfInterface(); }); AssemblyScanner.FindValidatorsInAssemblyContaining <RegistrationModelValidation>() .ForEach(result => exp.For(result.InterfaceType) .Singleton() .Use(result.ValidatorType)); }
public void ConfigureServices(IServiceCollection services) { services.AddPersistence(Configuration); services.AddApplication(); services.AddControllers() .AddNewtonsoftJson(); // Using application level FluentValidation (not api level) AssemblyScanner.FindValidatorsInAssemblyContaining <IGameStoreDbContext>().ForEach(pair => { services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType)); services.Add(ServiceDescriptor.Transient(pair.ValidatorType, pair.ValidatorType)); }); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = InvalidModelStateResponseHelper.InvalidModelStateResponse; }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "GameStore API", Version = "v1" }); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // AutoMapper services.AddAutoMapper(typeof(Startup)); // Validation AssemblyScanner.FindValidatorsInAssemblyContaining <Startup>().ForEach(pair => { services.Add(ServiceDescriptor.Scoped(pair.InterfaceType, pair.ValidatorType)); services.Add(ServiceDescriptor.Scoped(pair.ValidatorType, pair.ValidatorType)); }); // Mediatr services.AddScoped(typeof(IPipelineBehavior <,>), typeof(LoggingBehavior <,>)); services.AddScoped(typeof(IPipelineBehavior <,>), typeof(ValidatingBehavior <,>)); services.AddMediatR(typeof(Startup)); services.AddScoped <IMediatorService, MediatorService>(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); SetupDatabase(services); SetupAuthentication(services); SetupAuthorization(services); SetupCustomDependencies(services); }
public static void Register(HttpConfiguration config) { IKernel kernel = (IKernel)config.DependencyResolver.GetService(typeof(IKernel)); // Web API configuration and services FluentValidationModelValidatorProvider.Configure(config, cfg => cfg.ValidatorFactory = new NinjectValidationFactory(kernel)); AssemblyScanner.FindValidatorsInAssemblyContaining <Presentation>() .ForEach(result => kernel.Bind(result.InterfaceType) .To(result.ValidatorType)); //RabbitMQ configuration var bus = kernel.Get <IBus>(); bus.Receive <Course>("Test", m => OnMessage(m)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
private IKernel ConfigureValidation(HttpConfiguration config) { StandardKernel kernel = new StandardKernel(); // ---------- LayerLogic kernel.Bind <IService_Test>().To <Service_Test>(); kernel.Load <ModuleNinject_LogicLayer>(); // ---------- FluentValidation FluentValidationModelValidatorProvider.Configure(config, cfg => cfg.ValidatorFactory = new NinjectValidationFactory(kernel)); AssemblyScanner.FindValidatorsInAssemblyContaining <MTest_MainInfo>() .ForEach(result => kernel.Bind(result.InterfaceType) .To(result.ValidatorType)); // ---------- EasyNetQ kernel.RegisterEasyNetQ("host=127.0.0.1"); return(kernel); }
public FluentValidationMapping() { AssemblyScanner.FindValidatorsInAssemblyContaining <Program>().ForEach(pair => { For(pair.InterfaceType).Use(pair.ValidatorType); }); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add MediatR services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPerformanceBehavior <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestValidationBehavior <,>)); services.AddMediatR(); services .AddMvc(options => options.Filters.Add(typeof(CustomExceptionFilterAttribute))) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddFluentValidation(); AssemblyScanner.FindValidatorsInAssemblyContaining <Startup>().ForEach(pair => { // RegisterValidatorsFromAssemblyContaing does this: services.Add(ServiceDescriptor.Transient(pair.InterfaceType, pair.ValidatorType)); // Also register it as its concrete type as well as the interface type services.Add(ServiceDescriptor.Transient(pair.ValidatorType, pair.ValidatorType)); }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); }
public override void Initialize() { Func <CorporateCommerceRepository> commerceRepositoryFactory = () => new CorporateCommerceRepository(ConnectionStringName, _container.Resolve <AuditableInterceptor>()); _container.RegisterInstance <Func <ICorporateCommerceRepository> >(commerceRepositoryFactory); _container.RegisterType <ICommerceService, CorporateCommerceServiceImpl>(); _container.RegisterType <ICorporateCommerceService, CorporateCommerceServiceImpl>(); _container.RegisterType <ICorporateCommerceSearchService, CorporateCommerceServiceImpl>(); Func <CorporateMembersRepository> customerRepositoryFactory = () => new CorporateMembersRepository(ConnectionStringName, new EntityPrimaryKeyGeneratorInterceptor(), _container.Resolve <AuditableInterceptor>()); _container.RegisterInstance <Func <ICorporateMembersRepository> >(customerRepositoryFactory); _container.RegisterInstance <Func <ICustomerRepository> >(customerRepositoryFactory); _container.RegisterInstance <Func <IMemberRepository> >(customerRepositoryFactory); _container.RegisterType <IMemberService, CorporateMembersServiceImpl>(); _container.RegisterType <IMemberSearchService, MemberSearchServiceDecorator>(); // https://www.codeproject.com/Articles/326647/FluentValidation-and-Unity // https://stackoverflow.com/questions/25185272/how-can-i-automatically-register-all-my-fluent-validators-with-unity _container.RegisterType <IValidatorFactory, ValidatorFactory>(new ContainerControlledLifetimeManager()); var validators = AssemblyScanner.FindValidatorsInAssemblyContaining <InviteValidator>(); validators.ForEach(validator => _container.RegisterType(validator.InterfaceType, validator.ValidatorType, new ContainerControlledLifetimeManager())); }
public static void Register(HttpConfiguration config) { IKernel kernel = (IKernel)config.DependencyResolver.GetService(typeof(IKernel)); // Web API configuration and services FluentValidationModelValidatorProvider.Configure(config, cfg => cfg.ValidatorFactory = new NinjectValidationFactory(kernel)); //IValidator<Course> сканирует сборку и возвр список результатов, где вкачестве интерфейсов указан базовый тип // а в качестве типа валидатора - связанный с ним класс AssemblyScanner.FindValidatorsInAssemblyContaining <Course>() .ForEach(result => kernel.Bind(result.InterfaceType) .To(result.ValidatorType)); config.Filters.Add(new BadRequestFilterAttribute()); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); }
private IKernel ConfigureValidation(HttpConfiguration config) { var kernel = new StandardKernel(new LogicModule()); kernel.Load <AutoMapperModule>(); var _searchService = kernel.Get <ISearchService>(); //bus = kernel.Get<IBus>(); bus = RabbitHutch.CreateBus("host=localhost"); bus.Receive <LearningCourseDTO>("IndexService", b => _searchService.IndexCourse(b)); //bus.Advanced.Consume(bus.Advanced.QueueDeclare("BookService"), OnMessage); FluentValidationModelValidatorProvider .Configure(config, cfg => cfg.ValidatorFactory = new NinjectValidationFactory(kernel)); AssemblyScanner.FindValidatorsInAssemblyContaining <SearchQueryDTO>() .ForEach(result => kernel.Bind(result.InterfaceType) .To(result.ValidatorType)); kernel.RegisterEasyNetQ("host=localhost"); return(kernel); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services .AddMediatR(typeof(Startup).GetTypeInfo().Assembly); services .AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>)) .AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPostProcessorBehavior <,>)) .AddTransient(typeof(IPipelineBehavior <,>), typeof(SomePipelineBehavior <,>)); // Register all validators. Remove if using FluentValidation in model binding. AssemblyScanner.FindValidatorsInAssemblyContaining <Startup>() .ForEach(result => services.AddTransient(result.InterfaceType, result.ValidatorType)); services .AddMvcCore(config => { config.Filters.Add(typeof(ValidationExceptionAttribute)); config.Filters.Add(typeof(ModelStateValidationAttribute)); }) // Unccoment to enable DataAnnotations validation in model binding. // .AddDataAnnotations() .AddJsonFormatters(); // Unccoment to enable FluentValidation in model binding (not desirable in most cases). // .AddFluentValidation(config => // { // config.RegisterValidatorsFromAssemblyContaining(typeof(Startup)); // }); }
public override void Load() { Bind <ICacheService>().To <CacheService>(); Bind <IChannelService>().To <ChannelService>(); Bind <ILogicService>().To <LogicService>(); Bind <ISearchRequestService>().To <SearchRequestService>(); Bind <IStoryService>().To <StoryService>(); Bind <IVideoService>().To <VideoService>(); Bind <IServiceFactory>().ToFactory(); Bind <IChannelRepository>().To <ChannelRepository>(); Bind <ISearchRequestsRepository>().To <SearchRequestsRepository>(); Bind <IStoryRepository>().To <StoryRepository>(); Bind <IVideoRepository>().To <VideoRepository>(); Bind <YoutubeContext>().ToSelf().InThreadScope(); //Binding for IValidators AssemblyScanner.FindValidatorsInAssemblyContaining <SearchRequest>() .ForEach(result => Bind(result.InterfaceType) .To(result.ValidatorType)); var mapper = new Mapper(new MapperConfiguration(cfg => { cfg.CreateMap <SearchStoryDb, SearchStory>().ReverseMap(); cfg.CreateMap <SearchRequestDb, SearchRequest>().ReverseMap(); cfg.CreateMap <ResultVideoDb, ResultVideo>().ReverseMap(); cfg.CreateMap <ChannelDb, Channel>().ReverseMap(); })); Bind <IMapper>().ToConstant(mapper); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddFluentValidation(configuration => { // Setting up FluentValidation Validator Factory configuration.ValidatorFactory = new IncValidatorFactory(); AssemblyScanner.FindValidatorsInAssemblyContaining <User>().ForEach(result => { services.Add(ServiceDescriptor.Transient(result.InterfaceType, result.ValidatorType)); services.Add(ServiceDescriptor.Transient(result.ValidatorType, result.ValidatorType)); }); }); // Configure Core services services.ConfigureIncodingCoreServices(); // Configure Entity Framework (requires Incoding.Data.EF provider). You can use any existing provider implementation available in Incoding.Data.* on Nuget services.ConfigureIncodingEFDataServices(typeof(User), builder => { builder.UseSqlServer(Configuration.GetConnectionString("Main")); }); // Configure Incoding Framework MVC services services.ConfigureIncodingWebServices(); }
/// <summary> /// Initializes a new instance of the <see cref="Program"/> class. /// </summary> public Program() { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile("logging.json", optional: false, reloadOnChange: true) .Build(); var services = new ServiceCollection(); services.AddOptions(); services.Configure <AppOptions>(configuration.GetSection("AppOptions")); services.AddLogging(builder => { builder .AddConfiguration(configuration.GetSection("Logging")) .AddConsole(); }); // Add infrastructure services services.AddDefaultInfrastructure(); // Add compress services services.AddDefaultCompress(); // Add GIF services services.AddDefaultGif(); // Add ITK services services.AddDefaultItk(); services.AddSingleton <IAmiUnitOfWork, MockUnitOfWork>(); services.AddSingleton <IBackgroundService, MockBackgroundService>(); services.AddSingleton <IApplicationConstants, ApplicationConstants>(); services.AddSingleton <ICustomPrincipalProvider, MockPrincipalProvider>(); services.AddSingleton <IFileExtensionMapper, FileExtensionMapper>(); services.AddSingleton <IAppInfoFactory, AppInfoFactory>(); services.AddSingleton <IAppConfiguration, AppConfiguration>(); services.AddTransient <IDefaultJsonSerializer, DefaultJsonSerializer>(); // Add MediatR services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPerformanceBehavior <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestValidationBehavior <,>)); services.AddMediatR(typeof(ProcessCommandHandler).GetTypeInfo().Assembly); // Add FluentValidation AssemblyScanner.FindValidatorsInAssemblyContaining <ProcessCommandValidator>().ForEach(pair => { // filter out validators that are not needed here services.AddTransient(pair.InterfaceType, pair.ValidatorType); }); var serviceProvider = services.BuildServiceProvider(); Logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger <Program>(); Mediator = serviceProvider.GetService <IMediator>(); Configuration = serviceProvider.GetService <IAppConfiguration>(); }
private void RegisterValidators(Container container) { AssemblyScanner.FindValidatorsInAssemblyContaining <PessoaRequestValidator>() .ForEach(result => { container.Register(result.InterfaceType, result.ValidatorType, Lifestyle.Singleton); }); }
public void Register(IKernel kernel) { AssemblyScanner.FindValidatorsInAssemblyContaining <CustomerValidator>() .ForEach(result => { kernel.Register(Component.For(result.InterfaceType) .ImplementedBy(result.ValidatorType) .LifeStyle.Singleton); }); }
public ScanningRegistry() { var provider = LocalizationConfig.RegisterResources(Assembly.GetAssembly(typeof(StudentFriendlyNames))); For <ILocalizedStringProvider>().Use(provider); For <IUnitOfWork>().Use <UnitOfWork>(); For <IDataContext>().Use <SchoolContext>(); AssemblyScanner.FindValidatorsInAssemblyContaining <StudentEditValidator>() .ForEach(result => For(result.InterfaceType).Singleton().Use(result.ValidatorType)); }
public void Install(IWindsorContainer container, IConfigurationStore store) { container.Register(Component.For <IValidatorFactory>().ImplementedBy <WindsorValidatorFactory>()); AssemblyScanner.FindValidatorsInAssemblyContaining <UserValidator>() .ForEach(result => { container.Register(Component.For(result.InterfaceType) .ImplementedBy(result.ValidatorType).LifestylePerWebRequest()); }); }
protected override void Load(ContainerBuilder builder) { //register all validators AssemblyScanner .FindValidatorsInAssemblyContaining <AddOrderValidator>() .ForEach(x => builder.RegisterType(x.ValidatorType).As(x.InterfaceType).SingleInstance()); RegisterMediatR(builder); builder.RegisterType <Logger>().AsSelf(); }
public BaseTest() { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); var services = new ServiceCollection(); services.AddOptions(); services.Configure <AppSettings>(configuration.GetSection("AppSettings")); services.AddLogging(); services.AddScoped <IAmiUnitOfWork, InMemoryUnitOfWork>(); services.AddScoped <IIdGenService, IdGenService>(); services.AddScoped <IImageService, ImageService>(); services.AddScoped <IChunkedObjectUploader, ChunkedObjectUploader>(); services.AddSingleton <IApplicationConstants, ApplicationConstants>(); services.AddSingleton <ILoggerFactory, NullLoggerFactory>(); services.AddSingleton <IAppInfoFactory, MockAppInfoFactory>(); services.AddSingleton <IItkImageReaderFactory, ItkImageReaderFactory>(); services.AddSingleton <IAmiConfigurationManager, AmiConfigurationManager>(); services.AddSingleton <IFileSystemStrategy, FileSystemStrategy>(); services.AddSingleton <ITaskQueue, TaskQueue>(); services.AddSingleton <ITaskWorker, TaskWorker>(); services.AddTransient <ICompressibleReader, SharpCompressReader>(); services.AddTransient <ICompressibleWriter, SharpCompressWriter>(); services.AddTransient <IGifImageWriter, AnimatedGifImageWriter>(); services.AddTransient <IDefaultJsonSerializer, DefaultJsonSerializer>(); services.AddTransient <IDefaultJsonWriter, DefaultJsonWriter>(); services.AddTransient <IImageExtractor, ItkImageExtractor>(); services.AddTransient <ICompressibleExtractor, SharpCompressExtractor>(); // Add MediatR services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPerformanceBehavior <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestValidationBehavior <,>)); services.AddMediatR(typeof(ProcessCommandHandler).GetTypeInfo().Assembly); // Add FluentValidation AssemblyScanner.FindValidatorsInAssemblyContaining <ProcessCommandValidator>().ForEach(pair => { // filter out validators that are not needed here services.AddTransient(pair.InterfaceType, pair.ValidatorType); }); // Add DbContext services.AddDbContext <InMemoryDbContext>(options => { options.UseInMemoryDatabase(Guid.NewGuid().ToString()); options.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)); }); serviceProvider = services.BuildServiceProvider(); }
static ValidatorFactory() { foreach (var scanResult in AssemblyScanner.FindValidatorsInAssemblyContaining <BaseValidator>()) { var interfaceType = scanResult.InterfaceType; var validatorType = scanResult.ValidatorType; if (!validatorType.IsGenericType) { Validators.Add(interfaceType, (IValidator)Activator.CreateInstance(validatorType)); } } }
/// <summary> /// Register dependencies at the Application layer, with the service collection. /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> /// <returns></returns> public static IServiceCollection AddApplication(this IServiceCollection services, IConfiguration configuration) { services.AddAutoMapper(Assembly.GetExecutingAssembly()); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(LoggingPipeline <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(ValidationPipeline <,>)); AssemblyScanner.FindValidatorsInAssemblyContaining(typeof(IMarkerInterface)).ForEach(a => services.AddTransient(a.InterfaceType, a.ValidatorType)); return(services); }
private void Populate() { foreach (var v in AssemblyScanner.FindValidatorsInAssemblyContaining <IValidator>()) { var genericArguments = v.ValidatorType.BaseType.GetGenericArguments(); if (genericArguments.Length == 1) { var targetType = genericArguments[0]; _validatorsByType[targetType] = v.ValidatorType; } } }
/// <summary> /// Initializes a new instance of the <see cref="Program"/> class. /// </summary> public Program() { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile("logging.json", optional: false, reloadOnChange: true) .Build(); var services = new ServiceCollection(); services.AddOptions(); services.Configure <AppSettings>(configuration.GetSection("AppSettings")); services.AddLogging(builder => { builder .AddConfiguration(configuration.GetSection("Logging")) .AddConsole(); }); services.AddScoped <IIdGenService, IdGenService>(); services.AddScoped <IImageService, ImageService>(); services.AddScoped <IImageExtractor, ItkImageExtractor>(); services.AddScoped <IGifImageWriter, AnimatedGifImageWriter>(); services.AddScoped <IDefaultJsonWriter, DefaultJsonWriter>(); services.AddSingleton <IAmiUnitOfWork, MockUnitOfWork>(); services.AddSingleton <IApplicationConstants, ApplicationConstants>(); services.AddSingleton <IFileSystemStrategy, FileSystemStrategy>(); services.AddSingleton <IAppInfoFactory, AppInfoFactory>(); services.AddSingleton <IItkImageReaderFactory, ItkImageReaderFactory>(); services.AddSingleton <IAmiConfigurationManager, AmiConfigurationManager>(); services.AddTransient <IDefaultJsonSerializer, DefaultJsonSerializer>(); // Add MediatR services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPreProcessorBehavior <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestPerformanceBehavior <,>)); services.AddTransient(typeof(IPipelineBehavior <,>), typeof(RequestValidationBehavior <,>)); services.AddMediatR(typeof(ProcessCommandHandler).GetTypeInfo().Assembly); // Add FluentValidation AssemblyScanner.FindValidatorsInAssemblyContaining <ProcessCommandValidator>().ForEach(pair => { // filter out validators that are not needed here services.AddTransient(pair.InterfaceType, pair.ValidatorType); }); var serviceProvider = services.BuildServiceProvider(); Logger = serviceProvider.GetService <ILoggerFactory>().CreateLogger <Program>(); Mediator = serviceProvider.GetService <IMediator>(); Configuration = serviceProvider.GetService <IAmiConfigurationManager>(); }
/// <summary> /// Builds the container (private). /// </summary> /// <returns></returns> protected internal static IContainer UseIoc() { Logger.Trace("UseIoc: Initializing Container."); _initializing = true; try { Container = new Container(c => { c.For <System.Configuration.Abstractions.IConfigurationManager>() .Use(() => ConfigurationManager); c.Scan(s => { s.TheCallingAssembly(); s.AssembliesFromApplicationBaseDirectory(); s.IncludeNamespace("SammakEnterprise.JobSearch.Middle"); s.LookForRegistries(); s.WithDefaultConventions(); }); c.For <ISessionFactory>().Singleton().Use(ConfigureOrm()); c.For <ISession>().LifecycleIs(new ThreadLocalStorageLifecycle()).Use(ctx => ctx.GetInstance <ISessionFactory>().OpenSession()); c.For <IValidationFactory>().Use <ValidationFactory>().Ctor <IContainer>("container").Is(DependencyResolver.Container); c.For <IQueryFactory>().Use <QueryFactory>().Ctor <IContainer>("container").Is(DependencyResolver.Container); c.For <IEnumService>().Singleton().Use <EnumService>(); c.For <IValidator <AuditData> >().Singleton().Use <AuditData.AuditDataValidator>(); c.For <ICacheManager <Person> >().Singleton().Use(d => CacheFactory.FromConfiguration <Person>("cache", UseServiceCacheManagement())); //c.For<Core.MassTransit.IBusFactory>().Use<Core.MassTransit.BusFactory>(); //c.For<IAccessTokenService>().Singleton().Use<AccessTokenService>(); //c.For<IBackgroundJobClient>().Use<BackgroundJobClient>(); AssemblyScanner.FindValidatorsInAssemblyContaining <Person.PersonValidator>() .ForEach(r => { c.For(r.InterfaceType) .Singleton() .Use(r.ValidatorType); }); }); DependencyResolver.Container = Container; } finally { _initializing = false; } Logger.Trace("UseIoc: Container initialized."); return(Container); }
public static IServiceCollection AddValidatorsFromAssembly <T>(this IServiceCollection services) { // Register validators var scanner = AssemblyScanner.FindValidatorsInAssemblyContaining <T>(); foreach (var scanResult in scanner) { //Register as interface services.TryAdd(new ServiceDescriptor(scanResult.InterfaceType, scanResult.ValidatorType, ServiceLifetime.Singleton)); //Register as self services.TryAdd(new ServiceDescriptor(scanResult.ValidatorType, scanResult.ValidatorType, ServiceLifetime.Singleton)); } return(services); }
/// <summary> /// Creates Validators Configuration. /// </summary> /// <param name="configutation"></param> public static HttpConfiguration CreateValidation(this HttpConfiguration configutation) { IKernel kernel = (IKernel)configutation.DependencyResolver.GetService(typeof(IKernel)); // Web API configuration and services FluentValidationModelValidatorProvider.Configure(configutation, cfg => cfg.ValidatorFactory = new NinjectValidationFactory(kernel)); AssemblyScanner.FindValidatorsInAssemblyContaining(typeof(ReportCreateValidator)) .ForEach(result => kernel.Bind(result.InterfaceType).To(result.ValidatorType) ); return(configutation); }
protected override void Load(ContainerBuilder builder) { base.Load(builder); var assembly = GetType().Assembly; builder.RegisterApiControllers(assembly); AssemblyScanner .FindValidatorsInAssemblyContaining <AreaDtoValidator>() .ForEach(x => builder.RegisterType(x.ValidatorType) .As(x.InterfaceType) .SingleInstance()); builder.RegisterType <AutofacValidatorFactory>().As <IValidatorFactory>().SingleInstance(); }
private IKernel ConfigureValidation(HttpConfiguration config) { var kernel = new StandardKernel(new LogicModule(), new DataModule()); kernel.Load <MapperLoadModule>(); FluentValidationModelValidatorProvider.Configure(config, cfg => cfg.ValidatorFactory = new NinjectValidationFactory(kernel)); AssemblyScanner.FindValidatorsInAssemblyContaining <Models.CourseWeb>() .ForEach(result => kernel.Bind(result.InterfaceType) .To(result.ValidatorType)); kernel.RegisterEasyNetQ("host=localhost"); return(kernel); }
private IKernel ConfigureValidation(HttpConfiguration config) { var kernel = new StandardKernel(new LogicModule()); kernel.Load <AutoMapperLoad>(); // Web API configuration and services FluentValidationModelValidatorProvider.Configure(config, cfg => cfg.ValidatorFactory = new NinjectValidationFactory(kernel)); //IValidator<Course> AssemblyScanner.FindValidatorsInAssemblyContaining <Course>() .ForEach(result => kernel.Bind(result.InterfaceType) .To(result.ValidatorType)); return(kernel); }