public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddLogging();
            services.AddMultitenancy <Tenant, DefaultTenantResolver>();
            services.AddDbContext <TenantDbContext>(options => {
            });

            services.Scan(scanner =>
            {
                // scanner.AssembliesFromApplicationBaseDirectory();
                scanner.TheCallingAssembly();
                scanner.WithDefaultConventions();
            });
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddDbContext <AuthIdentityDbContext>();

            services
            .AddIdentity <MyIdentityUser, MyIdentityRole>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddEntityFrameworkStores <AuthIdentityDbContext>();;

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "LamarWithIdentityOnNet5", Version = "v1"
                });
            });
        }
Ejemplo n.º 3
0
        public void ConfigureContainer(ServiceRegistry registry)
        {
            var containerConfig = ContainerConfiguration.CreateFromAssembly(typeof(Startup).Assembly);

            ServiceProvisioningInitializer.PopulateRegistry(containerConfig, registry);

            var dropboxLocator = new Container(registry).GetService <IDropboxLocator>();
            var dropboxPath    = dropboxLocator.LocateDropboxPath();

            var completePath = Path.Combine(dropboxPath, "Apps", "LinkedInPoc", "Secrets.txt");
            var textLines    = File.ReadAllLines(completePath);

            registry.AddAuthentication(
                options =>
            {
                options.DefaultScheme          = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = "LinkedIn";
            })
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddLinkedIn("LinkedIn", options =>
            {
                options.ClientId     = textLines[0];
                options.ClientSecret = textLines[1];
                options.CallbackPath = new PathString("/signin-linkedin");

                options.SaveTokens = true;
                options.Scope.Clear();
                options.Scope.Add("r_liteprofile");
                options.Scope.Add("r_emailaddress");
                options.Scope.Add("w_member_social");

                options.Events.OnCreatingTicket = ticket =>
                {
                    // For some reason, HttpContext.GetTokenAsync("access_token") doesn't work;
                    LinkedInAccessTokenSingleton.Value = ticket.AccessToken;
                    return(Task.CompletedTask);
                };
            });

            registry.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));
            registry.AddDefaultIdentity <IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
            .AddEntityFrameworkStores <ApplicationDbContext>();
            registry.AddControllersWithViews();
            registry.AddRazorPages();
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddControllersWithViews().AddControllersAsServices().AddJsonOptions(x =>
            {
                x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                x.JsonSerializerOptions.MaxDepth = 255;
            });

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/dist";
            });
            services.AddEntityFrameworkSqlServer();

            services.AddSwaggerGen(c =>
            {
                c.AddServer(new OpenApiServer
                {
                    Url         = "http://localhost:5000",
                    Description = "HTTP endpoint"
                });
                c.AddServer(new OpenApiServer
                {
                    Url         = "https://localhost:5001",
                    Description = "HTTP endpoint with SSL"
                });
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Where Is My Fleet API", Version = "v1"
                });
                c.CustomSchemaIds((t) =>
                {
                    return(t.FullName.Replace("+", ""));
                });
            });

            //var applicationServicesAssembly = Assembly.Load();
            services.AddMediatR(typeof(WhereIsMyFleet.Services.CurrentUserModel).Assembly);
            services.For <IConfiguration>().Use(Configuration);
            services.AddDbContext <WhereIsMyFleetDbContext>(o => o.UseSqlServer(Configuration.GetConnectionString("WhereIsMyFleet")));
            services.SetupRegistries();
        }
Ejemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddControllers();

            services.Scan(s =>
            {
                s.TheCallingAssembly();
                s.WithDefaultConventions();
            });

            var assemblies =
                AppDomain
                .CurrentDomain
                .GetAssemblies()
                .Where(s => s.GetName().Name.StartsWith(nameof(Sigantha)))
                .ToArray();

            // Auto Mapper
            services.AddAutoMapper(assemblies);

            // Mediatr
            services.AddMediatR(assemblies);

            services.Scan(scanner =>
            {
                foreach (var assembly in assemblies)
                {
                    scanner.Assembly(assembly);
                }

                scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>));
            });

            // Need to add one for mediatr to see all of them
            services.For <IRequestHandler <TimelineGet.Query, TimelineGet.Result> >().Use <TimelineGet.Handler>();

            services.For <IMediator>().Use <Mediator>().Transient();
            services.For <ServiceFactory>().Use(ctx => ctx.GetInstance);

            // Db Contexts
            services.AddDbContext <SiganthaContext>(ServiceLifetime.Transient);
        }
Ejemplo n.º 6
0
        public void ConfigureContainer(ServiceRegistry services)
        {
            // Supports ASP.Net Core DI abstractions
            services.AddLogging();
            services.AddControllers();

            // Also exposes Lamar specific registrations
            // and functionality
            services.Scan(s =>
            {
                s.TheCallingAssembly();
                s.Assembly(typeof(AppDbContext).Assembly);
                s.WithDefaultConventions();
            });

            services.AddDbContext <AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SQLConnection")));

            services.AddCors();

            // This adds Lamar's validation to the
            // Oakton.AspNetCore environment check support
            services.CheckLamarConfiguration();
        }
Ejemplo n.º 7
0
        public void ConfigureContainer(ServiceRegistry serviceRegistry)
        {
            var logger = new LoggerConfiguration()
                         .ReadFrom.Configuration(Configuration)
                         .CreateLogger();

            logger.Information("Logger has been configured.");
            serviceRegistry.Scan(s =>
            {
                s.TheCallingAssembly();
                s.AssembliesFromApplicationBaseDirectory((assembly) => { return(assembly.FullName.Contains("kyc")); });
                s.AssemblyContainingType <IAlbumsDBContext>();
                s.WithDefaultConventions();
            });
            serviceRegistry.For <ILogger>().Use(logger);
            var mapperConfig = new MapperConfiguration(
                mc => mc.AddProfile(new MapperProfile())
                );

            serviceRegistry.AddSingleton(mapperConfig.CreateMapper());
            serviceRegistry.AddControllers();
            serviceRegistry.AddDbContext <AlbumsDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("AlbumsDBContext")), ServiceLifetime.Transient);
        }
Ejemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry 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 <FutureAgroIdentityDbContext>(options =>
                                                                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")), ServiceLifetime.Transient);

            services.AddIdentityCore <IdentityUser>(options =>
            {
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequireDigit           = false;
            })
            .AddDefaultTokenProviders()
            .AddSignInManager()
            .AddEntityFrameworkStores <FutureAgroIdentityDbContext>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
                options.DefaultChallengeScheme    = IdentityConstants.ApplicationScheme;
                options.DefaultSignInScheme       = IdentityConstants.ExternalScheme;
            })
            .AddCookie(cookieOptions =>
            {
                cookieOptions.AccessDeniedPath = "/Account/Login";
                cookieOptions.LoginPath        = "/Account/Login";
                cookieOptions.LogoutPath       = "/Account/Login";
            })
            .AddGoogle(options =>
            {
                // Provide the Google Client ID
                options.ClientId = "84213285064-3bu6c7f6iuov5e2nj71j8kp09ldsgg8p.apps.googleusercontent.com";
                // Register with User Secrets using:
                // dotnet user-secrets set "Authentication:Google:ClientId" "{Client ID}"

                // Provide the Google Client Secret
                options.ClientSecret = "USukES39oKelSIhWjI5Nj2W6";
                // Register with User Secrets using:
                // dotnet user-secrets set "Authentication:Google:ClientSecret" "{Client Secret}"

                options.ClaimActions.MapJsonKey("urn:google:picture", "picture", "url");
                options.ClaimActions.MapJsonKey("urn:google:locale", "locale", "string");
                options.SaveTokens = true;

                options.Events.OnCreatingTicket = ctx =>
                {
                    List <AuthenticationToken> tokens = ctx.Properties.GetTokens().ToList();

                    tokens.Add(new AuthenticationToken()
                    {
                        Name  = "TicketCreated",
                        Value = DateTime.UtcNow.ToString()
                    });

                    ctx.Properties.StoreTokens(tokens);

                    return(Task.CompletedTask);
                };
            })
            .AddIdentityCookies();

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

            services.ConfigureApplicationCookie(options =>
            {
                // Cookie settings
                options.Cookie.HttpOnly   = true;
                options.ExpireTimeSpan    = TimeSpan.FromMinutes(5);
                options.LoginPath         = "/Account/Login";
                options.AccessDeniedPath  = "/Account/Login";
                options.LogoutPath        = "/Account/Login";
                options.SlidingExpiration = true;
            });

            services.AddSignalR(options =>
            {
                //options.EnableDetailedErrors = true;
            });

            // Also exposes Lamar specific registrations
            // and functionality
            services.Scan(s =>
            {
                s.AssembliesAndExecutablesFromApplicationBaseDirectory();
                s.WithDefaultConventions();
            });

            services.AddSingleton <ILector, LectorTemperatura>();
            services.AddTransient <TemperaturaRepository>();

            services.AddSingleton <ILector, LectorHumedad>();
            services.AddTransient <HumedadRepository>();

            services.AddSingleton <ILector, LectorLuminosidad>();
            services.AddTransient <LuminosidadRepository>();

            services.AddSingleton <ILector, LectorCrecimiento>();
            services.AddSingleton <ILector, LectorPlantasMuertas>();
            services.AddTransient <PlantasRepository>();

            services.AddSingleton <ServicioCrecimiento>();
            services.AddSingleton <ServicioTemperatura>();
            services.AddSingleton <ServicioHumedad>();
            services.AddSingleton <ServicioLuminosidad>();
        }
Ejemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddControllers();

            services.Scan(s =>
            {
                s.TheCallingAssembly();
                s.WithDefaultConventions();
            });

            var assemblies =
                AppDomain
                .CurrentDomain
                .GetAssemblies()
                .Where(s => s.GetName().Name.StartsWith(nameof(Conglomerate)))
                .ToArray();

            // Auto Mapper
            services.AddAutoMapper(assemblies);

            // Services
            services.For <IIngredientService>().Use <IngredientService>();

            // Repositories
            services.For <IIngredientRepository>().Use <IngredientRepository>();

            // Mediatr
            services.AddMediatR(assemblies);

            services.Scan(scanner =>
            {
                foreach (var assembly in assemblies)
                {
                    scanner.Assembly(assembly);
                }

                scanner.ConnectImplementationsToTypesClosing(typeof(IRequestHandler <,>));
            });

            // For some reason we need to register one of the handlers for Lamar to register all of them
            services.For <IRequestHandler <IngredientGetAll.Query, IList <IngredientGetAll.Ingredient> > >().Use <IngredientGetAll.Handler>();

            services.For <IMediator>().Use <Mediator>().Transient();
            services.For <ServiceFactory>().Use(ctx => ctx.GetInstance);

            // Db Contexts
            services.AddDbContext <SandwichShopContext>(ServiceLifetime.Transient);

            // Hangfire
            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseStorage(new MySqlStorage(Configuration.GetConnectionString("Hangfire"), new MySqlStorageOptions()
            {
                TransactionIsolationLevel  = IsolationLevel.ReadCommitted,
                QueuePollInterval          = TimeSpan.FromSeconds(1),
                JobExpirationCheckInterval = TimeSpan.FromHours(1),
                CountersAggregateInterval  = TimeSpan.FromMinutes(5),
                PrepareSchemaIfNecessary   = true,
                DashboardJobListLimit      = 50000,
                TransactionTimeout         = TimeSpan.FromMinutes(1),
                TablePrefix = "Hangfire"
            })));

            services.AddHangfireServer(options =>
            {
                // Order determines priority
                options.Queues = new[] { JobQueues.API, JobQueues.DEFAULT };
            });

            services.For <IJobFactory>().Use <JobFactory>();
        }
Ejemplo n.º 10
0
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddLogging(config =>
            {
                config.ClearProviders();

                config.AddConfiguration(Configuration.GetSection("Logging"));
                config.AddApplicationInsights();
            });

            //Response Compression - https://docs.microsoft.com/en-us/aspnet/core/performance/response-compression?view=aspnetcore-5.0
            services.AddResponseCompression();

            services.AddCors(options =>
            {
                options.AddPolicy("SpecificOrigins",
                                  builder =>
                {
                    builder.WithOrigins("https://tmireact.azurewebsites.net", "https://theminiindex.com", "https://wwww.theminiindex.com", "http://localhost:3000")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSwaggerGen();

            services.AddDefaultIdentity <IdentityUser>()
            .AddRoles <IdentityRole>()
            .AddEntityFrameworkStores <MiniIndexContext>();

            services.AddHangfire(configuration => configuration
                                 .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                                 .UseSimpleAssemblyNameTypeSerializer()
                                 .UseRecommendedSerializerSettings()
                                 .UseSqlServerStorage(Configuration.GetConnectionString("HangfireConnection"), new SqlServerStorageOptions
            {
                CommandBatchMaxTimeout       = TimeSpan.FromMinutes(5),
                SlidingInvisibilityTimeout   = TimeSpan.FromMinutes(5),
                QueuePollInterval            = TimeSpan.Zero,
                UseRecommendedIsolationLevel = true,
                DisableGlobalLocks           = true
            }));
            services.AddHangfireServer();

            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddRazorOptions(ConfigureRazor);

            services.AddDbContext <MiniIndexContext>(ConfigureEntityFramework);

            string facebookAppId     = Configuration["Authentication:Facebook:AppId"];
            string facebookAppSecret = Configuration["Authentication:Facebook:AppSecret"];

            if (facebookAppId != null && facebookAppSecret != null)
            {
                services.AddAuthentication()
                .AddFacebook(facebookOptions =>
                {
                    facebookOptions.AppId     = facebookAppId;
                    facebookOptions.AppSecret = facebookAppSecret;
                });
            }

            services.AddTransient <IEmailSender, EmailSender>();
            services.Configure <AuthMessageSenderOptions>(Configuration);
            services.AddApplicationInsightsTelemetry();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <ITelemetryInitializer, TelemetryEnrichment>();
            services.AddApplicationInsightsTelemetryProcessor <AppInsightsFilter>();
            services.Configure <AzureStorageConfig>(Configuration.GetSection("AzureStorageConfig"));

            services.IncludeRegistry <CoreServices>();
            services.IncludeRegistry <WebAppServices>();
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureContainer(ServiceRegistry services)
        {
            services.AddMvc().AddControllersAsServices()
            .AddJsonOptions(x =>
            {
                x.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
                x.JsonSerializerOptions.MaxDepth = 255;
            });
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp";
            });

            services.AddEntityFrameworkSqlServer();

            #region setupAuthAndSwagger

            services.AddAuthentication(c =>
            {
                c.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                c.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // Clock skew compensates for server time drift.
                    // We recommend 5 minutes or less:
                    ClockSkew = TimeSpan.FromMinutes(5),
                    // Specify the key used to sign the token:
                    IssuerSigningKey    = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("VerticalToDoKeyVerticalToDoKeyVerticalToDoKey")),
                    RequireSignedTokens = true,
                    // Ensure the token hasn't expired:
                    RequireExpirationTime = true,
                    ValidateLifetime      = true,
                    // Ensure the token audience matches our audience value (default true):
                    ValidateAudience = false,
                    // Ensure the token was issued by a trusted authorization server (default true):
                    ValidateIssuer = false,
                };
            });
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "Vertical ToDo API", Version = "v1"
                });
                c.CustomSchemaIds((t) =>
                {
                    return(t.FullName.Replace("+", ""));
                });
                c.AddSecurityDefinition(JwtBearerDefaults.AuthenticationScheme, new OpenApiSecurityScheme
                {
                    Name         = "Authorization",
                    Type         = SecuritySchemeType.ApiKey,
                    Scheme       = JwtBearerDefaults.AuthenticationScheme,
                    BearerFormat = "JWT",
                    In           = ParameterLocation.Header,
                    Description  = "JWT Authorization header using the Bearer scheme."
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference
                            {
                                Type = ReferenceType.SecurityScheme,
                                Id   = JwtBearerDefaults.AuthenticationScheme
                            }
                        },
                        new string[] {}
                    }
                });
            });

            #endregion

            services.For <IConfiguration>().Use(Configuration);
            services.For <IHttpContextAccessor>().Use <HttpContextAccessor>();
            services.AddDbContext <VerticalToDoDbContext>(o => o.UseSqlServer(Configuration.GetConnectionString("VerticalToDo")));
            services.SetupRegistries();

            var c = new Container(services);
            var a = c.Model.For <AccountsController>().Default.DescribeBuildPlan();
            var q = c.WhatDoIHave();
        }