Пример #1
0
 public void ConfigureServices(IServiceCollection services)
 {
     VersioningConfiguration.AddConfiguration(services, 1, 0);
     DependencyInjectionConfiguration.RegisterServices(services);
     ApiConfiguration.AddConfiguration(services);
     SwaggerConfiguration.AddConfiguration(services);
 }
Пример #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton <IConfiguration>(Configuration);

            // Entity Framework context registration
            DependencyInjectionConfiguration.RegisterContext(services, HostingEnvironment);

            // Register Mediators
            DependencyInjectionConfiguration.RegisterMediator(services);

            // Register the Validators
            DependencyInjectionConfiguration.RegisterValidators(services);

            // Register all the query handlers with the related decorators
            DependencyInjectionConfiguration.RegisterQueryHandlers(services);

            // Register all the command handlers with the related decorators
            DependencyInjectionConfiguration.RegisterCommandHandlers(services);

            // Add framework services.
            services.AddOData();
            services.AddMvc()
            .AddJsonOptions(
                options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
                );
        }
Пример #3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // configure strongly typed settings objects from appsettings.json file
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);


            // configure DB
            services.AddDbContext <NebulaChatDbContext>(options =>
                                                        options.UseSqlServer(
                                                            Configuration.GetConnectionString("DefaultConnection")));

            // configure cors
            services.AddCors(options => options.AddPolicy("NebulaChatCorsPolicy",
                                                          builder =>
            {
                builder.AllowAnyMethod().AllowAnyHeader()
                .WithOrigins(appSettingsSection.Get <AppSettings>().ClientUrl)
                .AllowCredentials();
            }));

            // configure jwt authentication
            JwtAuthConfiguration.Configure(services, appSettingsSection);

            services.AddAutoMapper();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSignalR(options => options.EnableDetailedErrors = true);

            // Set dependency injection
            DependencyInjectionConfiguration.Configure(services);
        }
 public EditorWebSocketMiddleware(RequestDelegate next)
 {
     _next = next;
     _webSocketsService = DependencyInjectionConfiguration.GetContainer().GetInstance <IWebSocketsService>();
     _messageService    = DependencyInjectionConfiguration.GetContainer().GetInstance <IMessageService>();
     _messageProcessor  = DependencyInjectionConfiguration.GetContainer().GetInstance <IMessageProcessor>();
 }
Пример #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            //Setup para configuração do Swagger
            SwaggerConfiguration.AddSwagger(services);

            //Setup para configuração do EntityFramework
            EntityFrameworkConfiguration.AddEntityFramework(services, Configuration);

            //Setup para configuração do JWT
            JwtConfiguration.ConfigureServices(services, Configuration);

            //Setup para o MongoDB
            MongoDBConfiguration.AddMongoDBSetup(services, Configuration);

            //Injeção de dependência
            DependencyInjectionConfiguration.AddDependencyInjection(services);

            //Setup para o MediatR
            MediatRConfiguration.AddMediatRSetup(services);

            //Setup para o AutoMapper
            AutoMapperConfiguration.AddAutoMapperSetup(services);

            //Setup para o CORS
            CorsConfiguration.AddCors(services);
        }
Пример #6
0
 public void ConfigureServices(IServiceCollection services)
 {
     VersioningConfiguration.AddConfiguration(services, 1, 0);
     SwaggerConfiguration.AddConfiguration(services);
     IdentityConfiguration.AddConfiguration(services, Configuration.GetConnectionString("IdentityConnection"));
     ApiConfiguration.AddConfiguration(services);
     DependencyInjectionConfiguration.RegisterServices(services);
 }
Пример #7
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers();
     SwaggerConfiguration.AddSwagger(services);
     EntityFrameworkConfiguration.AddEntityFramework(services);
     JwtConfiguration.AddJwt(services, Configuration);
     DependencyInjectionConfiguration.AddDependencyInjection(services);
     AutoMapperConfiguration.AddAutoMapperSetup(services);
 }
Пример #8
0
        public void Configuration(IAppBuilder app)
        {
            DependencyInjectionConfiguration.Bootstrap(typeof(MvcApplication).Assembly);
            MongoModelMapper.Activate();

            ConfigureAuth(app);
            app.MapSignalR();
            Bootstrapper.Bootstrap();
            GlobalHost.HubPipeline.RequireAuthentication();
        }
Пример #9
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            DependencyInjectionConfiguration.InitializeContainer(app);
            loggerFactory.AddConsole(LogLevel.Debug);
            loggerFactory.AddDebug(LogLevel.Debug);

            app.UseWebSockets();
            app.Map("/editor", App => App.UseMiddleware <EditorWebSocketMiddleware>());
            app.UseMvc();
        }
Пример #10
0
    public static void Main(string[] args)
    {
        var services = new ServiceCollection();

        DependencyInjectionConfiguration.ConfigureDI(services);

        var serviceProvider = services.BuildServiceProvider();

        var receiver = serviceProvider.GetService <MyServiceInterface>();

        receiver.YourServiceMethod();
    }
Пример #11
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
     DependencyInjectionConfiguration.Configure(services);
     Log.Logger = new LoggerConfiguration()
                  .MinimumLevel.Information()
                  .WriteTo.Console()
                  .WriteTo.File(
         "logs/log.txt",
         rollingInterval: RollingInterval.Day,
         rollOnFileSizeLimit: true)
                  .CreateLogger();
 }
Пример #12
0
        } // public DependencyInjector(...)

        public void InjectServices(IServiceCollection services, DependencyInjectionConfiguration dependencyInjectionConfiguration)
        {
            if (dependencyInjectionConfiguration == null)
            {
                throw new ArgumentNullException(nameof(dependencyInjectionConfiguration));
            }

            InjectServices(services, dependencyInjectionConfiguration.TransientServices, ServiceLifetime.Transient);

            InjectServices(services, dependencyInjectionConfiguration.ScopedServices, ServiceLifetime.Scoped);

            InjectServices(services, dependencyInjectionConfiguration.SingletonServices, ServiceLifetime.Singleton);
        } // public void InjectServices(IServiceCollection services, DependencyInjectionConfiguration dependencyInjectionConfiguration)
Пример #13
0
        public void ConfigureServices(IServiceCollection services)
        {
            BindConfiguration(services);
            CorsConfiguration.Configure(services);

            IMvcBuilder mvcBuilder = services
                                     .AddAutoMapper()
                                     .AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            JsonFormattingConfiguration.Configure(mvcBuilder);

            DependencyInjectionConfiguration.Configure(services);
            SwaggerConfiguration.Configure(services);
        }
Пример #14
0
        private static void Main()
        {
            // configure IoC
            var dependencyInjectionConfiguration = new DependencyInjectionConfiguration(DependencyInjection.Container);

            dependencyInjectionConfiguration.Configure();

            // some client logic
            var client = new SimpleClient(DependencyInjection.Container.Resolve <ApplesProvider>());

            client.ShowApples();

            // wait for key press
            Console.ReadKey();
        }
Пример #15
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     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;
     });
     services.AddDbContext <MatchOrganizerContext>(options =>
     {
         options.UseSqlServer(Configuration.GetConnectionString("Database"));
     });
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddControllersAsServices().AddFluentValidation();
     services.AddTransient <IValidator <CreateMatchViewModel>, CreateMatchValidator>();
     return(DependencyInjectionConfiguration.Configure(services));
 }
Пример #16
0
 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     services.EnableSwagger();
     services.AddMvc(opts => opts.Filters.Add(new ValidateModelStateAttribute()))
     .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     services.AddHttpClient();
     services.EnableCors();
     services.EnableOptions(Configuration);
     services.EnableDatabase(Configuration);
     services.EnableIdentity();
     services.EnableAuth(Configuration);
     services.EnableMapping();
     services.EnableRabbitMq(Configuration);
     services.EnableDistrubutedMemoryCache(Configuration);
     services.EnableSchedulableJobs(Configuration);
     return(DependencyInjectionConfiguration.Configure(services));
 }
Пример #17
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();



            services.AddScoped <IConnectionBloodOrange, UnitOfWorkBloodOrange>(x =>
                                                                               new UnitOfWorkBloodOrange(Configuration.GetSection("Configuracoes").GetSection("Connection-BloodOrange").Value));


            services.AddScoped <IMessaging, Messages>(x => new Messages(Configuration.GetSection("Messages").Value));

            services.Configure <ApplicationConfiguration>(Configuration.GetSection("Aplicacao"));

            services.AddTransient <PerformaceFilters>();
            services.AddTransient <SecurityFilter>();



            AuthConfiguration.Register(services, Configuration);
            AutoMapperConfiguration.Register(services, Configuration);
            DependencyInjectionConfiguration.Register(services, Configuration);


            services.AddMvc(options =>
            {
                options.Filters.AddService <PerformaceFilters>();
                options.Filters.AddService <SecurityFilter>();
                options.Filters.Add(typeof(ErrorFilters));
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            }).SetCompatibilityVersion(CompatibilityVersion.Latest);
            SwaggerApiVersioningConfiguration.Register(services);

            var corsBuilder = new CorsPolicyBuilder()
                              .AllowAnyHeader()
                              .AllowAnyMethod()
                              .AllowAnyOrigin();

            services.AddCors(options =>
            {
                options.AddPolicy("SiteCorsPolicy", corsBuilder.Build());
            });
        }
Пример #18
0
        // 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.AddControllers();

            //configuração do swagger
            SwaggerConfiguration.AddSwagger(services);

            //configuração do EntityFramework
            EntityFrameworkConfiguration.AddPostgreSQLEntityFramework(services, Configuration);

            //configuração para autenticação por JWT
            JwtConfiguration.AddJwt(services, Configuration);

            //configuração para injeção de dependência
            DependencyInjectionConfiguration.AddDependencyInjection(services, Configuration);

            //configuração de CORS
            CorsConfiguration.AddCors(services);
        }
Пример #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();

            services.Configure <ApiConfiguration>(Configuration.GetSection("ApiConfiguration"));

            services.Configure <AppSettingsConfiguration>(Configuration.GetSection("AppSettings"));

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = new PathString("/Authentication/Auth");
            });
            services.AddScoped <UserManager>();
            AutoMapperConfiguration.Register(services, Configuration);
            DependencyInjectionConfiguration.Register(services, Configuration);

            services.AddSingleton <IFileProvider>(
                new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));
        }
Пример #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <SecurityContext>(options =>
                                                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            // Registrar todos os DI
            DependencyInjectionConfiguration.AddDIConfiguration(services);

            // Configurações de Autenticação, Autorização e JWT.
            services.AddSecurity(Configuration);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "API Security", Version = "v1"
                });
            });

            // AutoMapper
            AutoMapperConfiguration.AddAutoMapperSetup(services);
        }
Пример #21
0
        public BaseIdempotentIntegrationTest()
        {
            var serviceCollection = new ServiceCollection();
            var configuration     = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build();

            serviceCollection.AddSingleton <IConfiguration>(configuration);

            DependencyInjectionConfiguration.RegisterContext(serviceCollection, null);
            DependencyInjectionConfiguration.RegisterMediator(serviceCollection);
            DependencyInjectionConfiguration.RegisterValidators(serviceCollection);
            DependencyInjectionConfiguration.RegisterQueryHandlers(serviceCollection);
            DependencyInjectionConfiguration.RegisterCommandHandlers(serviceCollection);

            ServiceProvider = serviceCollection.BuildServiceProvider();

            // Context provider is used by the Persisters
            // This need to be the same used by the idempotent tests or the database will
            // be locked by the transaction
            ContextProvider.ServiceProvider = ServiceProvider;
        }
Пример #22
0
        private static void Configure(IServiceCollection services, ILogger logger, IConfigurationRoot configuration)
        {
            logger.LogInformation("Configuring services.");

            // Scope (service lifetime) notes:
            // Singleton (0)    Specifies that a single instance of the service will be created.
            //                  => objects are the same for every object and every request.
            // Scoped (1)       Specifies that a new instance of the service will be created for each scope.
            //                  In ASP.NET Core applications a scope is created around each server request.
            //                  => objects are the same within a request, but different across different requests.
            //Transient (2)     Specifies that a new instance of the service will be created every time it is requested.
            //                  => objects are always different; a new instance is provided to every controller and every service.

            // Configuration settings should always come first, followed by logging
            services.AddSingleton <IConfiguration>(configuration);

            // TODO: Improve the way we are logging this and the below after chunk
            //var serviceList = services.OrderBy(_ => _.Lifetime).ToList();
            //using (System.IO.StreamWriter sw = new System.IO.StreamWriter("services-before.txt"))
            //{
            //    sw.AutoFlush = true;

            //    foreach (var item in serviceList)
            //    {
            //        sw.WriteLine("{0} {1} {2} {3} {4}",
            //            item.Lifetime,
            //            item.ServiceType,
            //            item.ImplementationFactory,
            //            item.ImplementationType,
            //            item.ImplementationInstance
            //            );
            //    }
            //}

            // Logging
            services.AddLogging(_ =>
            {
                if (File.Exists("NLog.config")) // Use NLog only if NLog.config file is found
                {
                    _.AddNLog(configuration);
                }

                if (configuration.IsTrue("Application:EnableSerilog"))
                {
                    _.AddSerilog(new LoggerConfiguration()
                                 .ReadFrom.Configuration(configuration)
                                 .CreateLogger());
                }

                if (configuration.IsTrue("Application:EnableDefaultConsoleLogging"))
                {
                    _.AddConsole();
                }
            });

            // TODO: Improve the way we are logging this
            //serviceList = services.OrderBy(_ => _.Lifetime).ToList();
            //using (System.IO.StreamWriter sw = new System.IO.StreamWriter("services-after.txt"))
            //{
            //    sw.AutoFlush = true;

            //    foreach (var item in serviceList)
            //    {
            //        sw.WriteLine("{0} {1} {2} {3} {4}",
            //            item.Lifetime,
            //            item.ServiceType,
            //            item.ImplementationFactory,
            //            item.ImplementationType,
            //            item.ImplementationInstance
            //            );
            //    }
            //}

            DependencyInjectionConfiguration dependencyInjectionConfiguration = new DependencyInjectionConfiguration();

            configuration.GetSection("DependencyInjection").Bind(dependencyInjectionConfiguration);

            DependencyInjector dependencyInjector = new DependencyInjector(logger);

            dependencyInjector.InjectServices(services, dependencyInjectionConfiguration);

#pragma warning disable S125 // Sections of code should not be commented out
            // New way of doing this?
            //services.Configure<DependencyInjectionConfiguration>(configuration.GetSection("DependencyInjection"));



            // PLACEHOLDER: services.Configure<ConnectionStrings>(config.GetSection("ConnectionStrings"));

            // Configure logging

            //services.AddLogging(builder =>
            //{
            //    builder.AddConsole();
            //    builder.AddDebug();
            //});


            //var servicesConfiguration = configuration.Get<ServicesConfiguration>();

            //foreach (var service in servicesConfiguration.Singleton)
            //{
            //    services.AddSingleton(Type.GetType(service.Service), Type.GetType(service.Implementation));
            //}

            //foreach (var service in servicesConfiguration.Transient)
            //{
            //    services.AddTransient(Type.GetType(service.Service), Type.GetType(service.Implementation));
            //}


            // Add business injectables
            //DependencyInjector dependencyInjector = new DependencyInjector(dependencyInjectionConfiguration, );
            //DependencyInjector.InjectServices();

            //services.AddTransient<IApplication, DummyApplication>();

            //            Microsoft.Extensions.DependencyInjection.ServiceDescriptor
            //Microsoft.Extensions.DependencyInjection.ServiceLifetime

            //                    ServiceDescriptor sd = new ServiceDescriptor(
            //serviceType,
            //implementationType,
            //serviceLifetime);
            //        services.Add(sd);


#pragma warning restore S125 // Sections of code should not be commented out


            // IMPORTANT! Register our application entry point
            services.AddTransient <Program>();

            logger.LogInformation("Services set.");
        }
Пример #23
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllers();
     SwaggerConfiguration.AddSwagger(services);
     DependencyInjectionConfiguration.AddDependencyInjection(services, Configuration);
 }
Пример #24
0
 public void Initialize(IUnityContainer container)
 {
     dependencyInjectionConfiguration = new DependencyInjectionConfiguration(container);
     dependencyInjectionConfiguration.Configure();
 }
Пример #25
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllersWithViews();
     EntityFrameworkConfiguration.AddEntityFramework(services, Configuration);
     DependencyInjectionConfiguration.AddDependencyInjection(services);
 }
Пример #26
0
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
     DependencyInjectionConfiguration.IntegrateSimpleInjector(services);
 }
Пример #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            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;
            });

            services.AddDbContext <OrhedgeContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("Database"));
            });

            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services
            .AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(opts =>
            {
                opts.Cookie.IsEssential       = true;
                opts.LoginPath                = "/Home/Login";
                opts.AccessDeniedPath         = "/Home/AccessDenied";
                opts.SlidingExpiration        = true;
                opts.ExpireTimeSpan           = TimeSpan.FromMinutes(30);
                opts.Events.OnRedirectToLogin = async ctx =>
                {
                    bool apiCall = ctx.Request.Path.StartsWithSegments("/api");

                    if (apiCall)
                    {
                        ctx.Response.StatusCode = StatusCodes.Status401Unauthorized;
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }


                    await Task.CompletedTask;
                };
                opts.Events.OnRedirectToAccessDenied = async ctx =>
                {
                    bool apiCall = ctx.Request.Path.StartsWithSegments("/api");

                    if (apiCall)
                    {
                        ctx.Response.StatusCode = StatusCodes.Status403Forbidden;
                    }
                    else
                    {
                        ctx.Response.Redirect(ctx.RedirectUri);
                    }

                    await Task.CompletedTask;
                };
            });

            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddControllersAsServices()
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(
                opts =>
                opts.DataAnnotationLocalizerProvider =
                    (type, factory) => factory.Create(typeof(SharedResource)));
            services.AddSignalR();
            return(DependencyInjectionConfiguration.Configure(services));
        }
Пример #28
0
 private void InitializeDependencyInjection()
 {
     dependencyInjectionConfiguration = new DependencyInjectionConfiguration(DependencyInjection.Container);
     dependencyInjectionConfiguration.Configure();
 }
Пример #29
0
 protected void Application_Start()
 {
     GlobalConfiguration.Configure(WebApiConfig.Register);
     GlobalConfiguration.Configuration.DependencyResolver = DependencyInjectionConfiguration.GetDependencyResolver();
 }