Ejemplo n.º 1
0
 private static void RegisterServices(IServiceCollection services)
 {
     // Adding dependencies from another layers (isolated from Presentation)
     NativeInjectorBootStrapper.RegisterServices(services);
 }
Ejemplo n.º 2
0
 private void RegisterServices(IServiceCollection services)
 {
     NativeInjectorBootStrapper.RegisterServices(services, Configuration);
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Injeta as dependências do projeto
 /// </summary>
 /// <param name="services"></param>
 public static void AddDependencyInjection(this IServiceCollection services)
 {
     NativeInjectorBootStrapper.RegisterServices(services);
     ExemploBaseEFInjectorBootStrapper.RegisterServices(services);
 }
Ejemplo n.º 4
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services"></param>
        public void ConfigureServices(IServiceCollection services)
        {
            ConnectionStrings.BancoDadosConnection = Configuration.GetConnectionString("BancoDadosConnection");

            if (enviroment.IsDevelopment())
            {
                services.AddMvc(config =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                })
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Formatting = Formatting.Indented;
                })
                .AddApplicationPart(typeof(UsuarioController).GetTypeInfo().Assembly)
                .AddControllersAsServices();
            }
            else
            {
                services.AddMvc(config =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();
                    config.Filters.Add(new AuthorizeFilter(policy));
                })
                .AddJsonOptions(options =>
                {
                    options.SerializerSettings.Formatting = Formatting.Indented;
                })
                .AddApplicationPart(typeof(UsuarioController).GetTypeInfo().Assembly)
                .AddControllersAsServices();
            }

            services.AddSingleton <JwtSettings>();
            services.AddScoped <IJwtService, JwtService>();

            var jwtSettings = services.BuildServiceProvider().GetRequiredService <JwtSettings>();

            services
            .AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(jwtBearerOptions =>
            {
                jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidateActor            = true,
                    ValidateAudience         = true,
                    ValidateLifetime         = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = jwtSettings.Issuer,
                    ValidAudience    = jwtSettings.Audience,
                    IssuerSigningKey = jwtSettings.SigningCredentials.Key
                };
            });

            services.AddAutoMapper();
            AutoMapperConfiguration.RegisterMappings();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = $"NetCore - BackEnd Api - {enviroment.EnvironmentName}", Version = "v1"
                });
                var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Swagger.xml");
                c.IncludeXmlComments(filePath);
            });

            services.AddOptions();

            services.AddCors(o => o.AddPolicy("Cors", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            // Registrar todos os DI
            NativeInjectorBootStrapper.RegisterServices(services);
        }
Ejemplo n.º 5
0
 private static void RegisterServices(IServiceCollection services, IConfiguration configuration)
 {
     NativeInjectorBootStrapper.RegisterServices(services, configuration);
 }
Ejemplo n.º 6
0
        private static void RegisterServices(IServiceCollection services)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            NativeInjectorBootStrapper.RegisterServices(services);
        }
Ejemplo n.º 7
0
 private static void RegisterServices(IServiceCollection services)
 {
     // Injeção de dependencia na camada de CrossCutting
     NativeInjectorBootStrapper.RegisterServices(services);
 }
Ejemplo n.º 8
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddControllersWithViews();
     NativeInjectorBootStrapper.RegisterServices(services);
     services.AddMediatR(typeof(Startup));
 }
Ejemplo n.º 9
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)
        {
            #region 基本注入
            services.Configure <AppConfig>(Configuration);

            services.AddAuthentication("user").AddCookie("user", options =>
            {
                options.LoginPath = new PathString("/user/login");
                options.Events    = new CookieAuthenticationEvents
                {
                    OnValidatePrincipal = context => {
                        context.HttpContext.User = context.Principal;
                        return(Task.CompletedTask);
                    }
                };
            });

            services.AddAuthentication("admin").AddCookie("admin", options =>
            {
                options.AccessDeniedPath = "/Admin/Denied";
                options.LoginPath        = "/Admin/Login";
            });

            services.AddRazorPages(options => {
                options.Conventions.AddPageRoute("/User/Login", "");
            }).AddMvcOptions(options =>
            {
                options.MaxModelValidationErrors = 50;
                options.ModelBindingMessageProvider.SetValueMustNotBeNullAccessor(x => "请输入内容");
                options.ModelBindingMessageProvider.SetValueIsInvalidAccessor(x => $"输入值'{x}'无效");
                options.ModelBindingMessageProvider.SetAttemptedValueIsInvalidAccessor((x, y) => $"输入值'{x}'无效");
                options.ModelBindingMessageProvider.SetValueMustBeANumberAccessor((x) => "只能输入数字");
                options.ModelBindingMessageProvider.SetMissingBindRequiredValueAccessor((x) => $"缺少属性 '{x}'");
                options.ModelBindingMessageProvider.SetMissingKeyOrValueAccessor(() => "请输入内容");
                options.ModelBindingMessageProvider.SetUnknownValueIsInvalidAccessor((x) => "输入值无效");
                options.ModelBindingMessageProvider.SetMissingRequestBodyRequiredValueAccessor(() => "RequestBody 不能为空");
                options.ModelBindingMessageProvider.SetNonPropertyValueMustBeANumberAccessor(() => "只能输入数字");
                options.ModelBindingMessageProvider.SetNonPropertyAttemptedValueIsInvalidAccessor((x) => $"输入值'{x}'无效");
                options.ModelBindingMessageProvider.SetNonPropertyUnknownValueIsInvalidAccessor(() => "输入值无效");
            });;

            var    dataProvide      = Configuration.GetValue <string>("DataProvider").ToLower();
            string connectionString = Configuration.GetConnectionString(dataProvide);
            #endregion

            services.AddDbContext <EmpriseDbContext>(x => {
                switch (dataProvide)
                {
                case "mssql":

                    x.UseSqlServer(connectionString);
                    break;

                case "mysql":
                    x.UseMySql(connectionString);
                    break;

                case "postgresql":
                    x.UseNpgsql(connectionString);
                    break;

                default:
                    throw new Exception("数据库链接配置错误,请检查appsettings.json文件!");
                }
            });

            services.AddCap(x =>
            {
                switch (dataProvide)
                {
                case "mssql":
                    x.UseSqlServer(connectionString);
                    break;

                case "mysql":
                    x.UseMySql(connectionString);
                    break;

                case "postgresql":
                    x.UsePostgreSql(connectionString);
                    break;

                default:
                    throw new Exception("数据库链接配置错误,请检查appsettings.json文件!");
                }

                x.Version = "v1";
                x.SucceedMessageExpiredAfter = 1 * 3600;
                x.ConsumerThreadCount        = 5;
                x.FailedRetryCount           = 3;
                x.FailedRetryInterval        = 30;
                x.UseInMemoryMessageQueue();
            });

            //自动注入
            services.AutoRegister();

            //手动注入,无法自动注入的
            NativeInjectorBootStrapper.RegisterServices(services);
        }
Ejemplo n.º 10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //nginx
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders =
                    ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
            });

            services.AddHsts(options =>
            {
                options.Preload           = true;
                options.IncludeSubDomains = true;
                options.MaxAge            = TimeSpan.FromDays(60);
                options.ExcludedHosts.Add("ddd.neters.com");
            });


            services.AddSameSiteCookiePolicy();

            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;
            });


            // IdentityServer4 注入
            if (Configuration["Authentication:IdentityServer4:Enabled"].ObjToBool())
            {
                System.Console.WriteLine("当前授权模式是:Ids4");
                services.AddId4OidcSetup(Configuration);
            }
            else
            {
                System.Console.WriteLine("当前授权模式是:Identity");
                services.AddIdentitySetup(Configuration);
            }

            // Automapper 注入
            services.AddAutoMapperSetup();

            services.AddControllersWithViews();

            services.AddAuthorization(options =>
            {
                options.AddPolicy("CanWriteStudentData", policy => policy.Requirements.Add(new ClaimRequirement("Students", "Write")));
                options.AddPolicy("CanRemoveStudentData", policy => policy.Requirements.Add(new ClaimRequirement("Students", "Remove")));
                options.AddPolicy("CanWriteOrRemoveStudentData", policy => policy.Requirements.Add(new ClaimRequirement("Students", "WriteOrRemove")));
            });

            // Adding MediatR for Domain Events
            // 领域命令、领域事件等注入
            // 引用包 MediatR.Extensions.Microsoft.DependencyInjection
            services.AddMediatR(typeof(Startup));

            // .NET Core 原生依赖注入
            // 单写一层用来添加依赖项,从展示层 Presentation 中隔离
            NativeInjectorBootStrapper.RegisterServices(services);
        }
Ejemplo n.º 11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void 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.AddSingleton(new Appsettings(Env.ContentRootPath));

            services.AddSingleton <ILoggerProvider, Log4NetLoggerProvider>();

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         //options.UseSqlServer(BaseDBConfig.GetConnectionString(Configuration.GetConnectionString("DefaultConnectionFile"), Configuration.GetConnectionString("DefaultConnection")))
                                                         options.UseSqlServer(BaseDBConfig.ConnectionString)
                                                         );

            //services.AddIdentity<ApplicationUser, IdentityRole>()
            //    .AddEntityFrameworkStores<ApplicationDbContext>()
            //    .AddDefaultTokenProviders();

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                //cookie默认有效时间为8个小时
                options.ExpireTimeSpan = TimeSpan.FromMinutes(480);
                //登录路径:这是当用户试图访问资源但未经过身份验证时,程序将会将请求重定向到这个相对路径
                options.LoginPath = new PathString("/Account/Login");
                //重定向通常包括 returnUrl 查询字符串参数,以便用户在成功登录后可以返回到最初请求的 URL。 用户进行身份验证后,会重定向到最初请求的 URL。
                //默认参数名称是“ReturnUrl”,可以通过 ReturnUrlParameter 重新设置。
                //options.ReturnUrlParameter = "ReturnUrl";
                options.LogoutPath = new PathString("/Account/Logout");
                //禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径
                options.AccessDeniedPath = new PathString("/Home/Index");

                options.Cookie = new CookieBuilder
                {
                    HttpOnly = true,
                    Name     = "AGooday.DncZero.Identity",
                    Path     = "/"
                };
                //o.DataProtectionProvider = null;//如果需要做负载均衡,就需要提供一个Key
            });

            // Automapper 注入
            services.AddAutoMapperSetup();

            //services.AddControllersWithViews();
            services.AddMvc(cfg =>
            {
                cfg.Filters.Add(new AuthorityFilter());
                //cfg.OutputFormatters.Clear();
                //cfg.OutputFormatters.Add(new JsonOutputFormatter(new JsonSerializerSettings()
                //{
                //    ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                //}, ArrayPool<char>.Shared));
            })
            //.AddRazorOptions(options =>
            //{
            //    //修改 Razor 的 ViewLocationFormats 集合,以自定义视图搜索路径。 例如,将新项添加到集合,以搜索路径“/Components/{视图组件名称}/{视图名称}”中的视图
            //    options.ViewLocationFormats.Add("/{0}.cshtml");//占位符“{0}”表示路径“Components/{视图组件名称}/{视图名称}”
            //})
            ;

            //services.AddAuthorization(options =>
            //{
            //    options.AddPolicy("CanWriteUsersData", policy => policy.Requirements.Add(new ClaimRequirement("Users", "Write")));
            //    options.AddPolicy("CanRemoveUsersData", policy => policy.Requirements.Add(new ClaimRequirement("Users", "Remove")));
            //    options.AddPolicy("CanWriteOrRemoveUsersData", policy => policy.Requirements.Add(new ClaimRequirement("Users", "WriteOrRemove")));
            //});

            // Adding MediatR for Domain Events
            // 领域命令、领域事件等注入
            // 引用包 MediatR.Extensions.Microsoft.DependencyInjection
            //services.AddMediatR(typeof(MyxxxHandler));//单单注入某一个处理程序
            //或
            services.AddMediatR(typeof(Startup));//目的是为了扫描Handler的实现对象并添加到IOC的容器中

            // .NET Core 原生依赖注入
            // 单写一层用来添加依赖项,从展示层 Presentation 中隔离
            NativeInjectorBootStrapper.RegisterServices(services);
        }
Ejemplo n.º 12
0
 public static void AddDependencyInjection(this IServiceCollection services, IConfiguration configuration)
 {
     NativeInjectorBootStrapper.RegisterServices(services, configuration);
 }
Ejemplo n.º 13
0
 public static void AddDependencyInjectionSetup(this IServiceCollection service)
 {
     NativeInjectorBootStrapper.RegisterServices(service);
 }
Ejemplo n.º 14
0
        private static void RegisterService(IServiceCollection services)
        {
            var parametros = new Dictionary <Enum, string>();

            NativeInjectorBootStrapper.RegisterServices(services, parametros);
        }
Ejemplo n.º 15
0
 public static void AddDIConfiguration(this IServiceCollection services)
 {
     NativeInjectorBootStrapper.RegisterServices(services);
 }
Ejemplo n.º 16
0
 private static void RegisterServices(IServiceCollection services)
 => NativeInjectorBootStrapper.RegisterServices(services);
Ejemplo n.º 17
0
 public void RegisterServices(IServiceCollection services)
 {
     NativeInjectorBootStrapper.RegisterServices(services);
 }
Ejemplo n.º 18
0
 private static void RegisterServices(IServiceCollection services, string apiKey)
 {
     NativeInjectorBootStrapper.RegisterServices(services, apiKey);
 }