コード例 #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(o => o.AddPolicy("AllowAll", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));

            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(ValidateModel));
            })
            .AddFluentValidation(fvc =>
                                 fvc.RegisterValidatorsFromAssemblyContaining <Startup>());

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "API Talentos Easycom",
                    Description    = "API para gerenciamento e manutencao de talentos da Easycom",
                    TermsOfService = "None",
                    Contact        = new Contact()
                    {
                        Name = "Giancarlos A. Macedo", Email = "*****@*****.**", Url = "www.gianaugusto.com.br"
                    }
                });
            });

            MapperInitializer.Init();

            services.AddSingleton(Mapper.Configuration);
            services.AddScoped <IMapper>(sp => new Mapper(sp.GetRequiredService <AutoMapper.IConfigurationProvider>(), sp.GetService));
            services.AddScoped <DbContext, Context>();

            var connString = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <Context>(o => o.UseSqlServer(connString));
            services.AddScoped <ITalentoRepository, TalentoRepository>();
            services.AddScoped <IConhecimentoRepository, ConhecimentoRepository>();
        }
コード例 #2
0
ファイル: Startup.cs プロジェクト: ShaoHans/SmartCqrs
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.Filters.Add(typeof(HttpGlobalExceptionFilter));
            })
            .AddJsonOptions(options =>
            {
                // API接口返回日期时间类型的数据时使用自定义格式化
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

            services.Configure <AppSettings>(Configuration);

            #region WebApi版本控制及Swagger文档

            services.AddMvcCore().AddApiExplorer().AddVersionedApiExplorer(options =>
            {
                options.GroupNameFormat = "'v'VVV";
            });

            services.AddApiVersioning(options =>
            {
                options.ReportApiVersions = true;
                options.AssumeDefaultVersionWhenUnspecified = true;
                options.DefaultApiVersion = new ApiVersion(1, 0);
                //options.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader(), new HeaderApiVersionReader("api-version"));
                options.ApiVersionReader = new HeaderApiVersionReader("api-version");
            });

            services.AddSwaggerGen(options =>
            {
                var provider = services.BuildServiceProvider()
                               .GetRequiredService <IApiVersionDescriptionProvider>();

                foreach (var description in provider.ApiVersionDescriptions)
                {
                    options.SwaggerDoc(
                        description.GroupName,
                        new Info()
                    {
                        Title   = $"api接口{description.ApiVersion}版本",
                        Version = description.ApiVersion.ToString()
                    });
                }

                List <string> xmlDocs = new List <string>
                {
                    "SmartCqrs.API.xml",
                    "SmartCqrs.Application.xml",
                    "SmartCqrs.Query.xml",
                    "SmartCqrs.Infrastructure.xml",
                    "SmartCqrs.Enumeration.xml"
                };
                foreach (var xmlDoc in xmlDocs)
                {
                    var xmlDocPath = Path.Combine(AppContext.BaseDirectory, xmlDoc);
                    if (File.Exists(xmlDocPath))
                    {
                        options.IncludeXmlComments(xmlDocPath);
                    }
                }

                options.OperationFilter <SwaggerDefaultValues>();
                options.DocumentFilter <SwaggerHideInDocsFilter>();
            });

            #endregion

            // 参考文章:https://www.cnblogs.com/RainingNight/p/jwtbearer-authentication-in-asp-net-core.html
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                var jwtSettings = new JwtSettings();
                Configuration.GetSection("JwtSettings").Bind(jwtSettings);
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecurityKey)),
                    ValidateAudience         = true,
                    ValidAudience            = jwtSettings.Audience,
                    ValidateIssuer           = true,
                    ValidIssuer = jwtSettings.Issuer
                };
            });

            services.AddDbContext <SmartBlogPostgresqlDbContext>(options =>
            {
                options.UseNpgsql(Configuration.GetConnectionString("SmartBlogPostgresql"));
            });
            services.AddScoped(sp => { return(new DapperContext(Configuration.GetConnectionString("SmartBlogPostgresql"))); });
            services.AddMediatR(typeof(BaseCommandHandler).GetTypeInfo().Assembly);
            services.AddScoped <IUnitOfWork, EfCoreUnitOfWork>();
            services.AddTransient(typeof(IRepository <>), typeof(EfCoreRepositoryBase <>));
            services.AddTransient(typeof(IUserRepository), typeof(UserRepository));
            services.AddTransient(typeof(IUserAssetRepository), typeof(UserAssetRepository));
            services.AddSingleton <ILoggerManager, NLoggerManager>();
            services.AddTransient(typeof(ICarQuery), typeof(CarQuery));
            services.AddTransient(typeof(IUserQuery), typeof(UserQuery));
            services.Configure <CommonserviceUrlModel>(Configuration.GetSection("CommonserviceUrl"));
            MapperInitializer.Init();

            services.AddHttpClient();
            services.AddHttpClient <TongHangBrokerCommonServiceClient>(client =>
            {
                client.BaseAddress = new Uri(Configuration.GetSection("IdentityServer:CommonServiceHost").Value);
            });
            services.AddHttpClient <TongHangBrokerAuthServiceClient>(client =>
            {
                client.BaseAddress = new Uri(Configuration.GetSection("IdentityServer:AuthTokenUrl").Value);
            });

            services.AddTransient <IJwtService, JwtService>();
        }