示例#1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //user bearer token
            ConfigureJwtAuthService(services);

            //auto mapper
            AutoMapperConfig.Build();

            services.AddSwaggerGen(c => {
                c.SwaggerDoc("v1", new Info {
                    Title = "You api title", Version = "v1"
                });
                c.AddSecurityDefinition("Bearer", new ApiKeyScheme {
                    In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey"
                });
                c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > {
                    { "Bearer", Enumerable.Empty <string>() },
                });
            });

            // add cors
            services.AddCors(o => o.AddPolicy("AllowAllCorsPolicy", builder =>
            {
                builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
            }));
            services.Configure <MvcOptions>(options =>
            {
                options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAllCorsPolicy"));
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Latest);
            //// Add Autofac
            var containerBuilder = new ContainerBuilder();

            containerBuilder.Populate(services);
            containerBuilder.RegisterAssemblyTypes(Assembly.Load("Repository"))
            .Where(x => x.Name.EndsWith("Repository"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            containerBuilder.RegisterAssemblyTypes(Assembly.Load("Service"))
            .Where(x => x.Name.EndsWith("Service"))
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            //use db
            containerBuilder.RegisterType <ApplicationDbContext>().AsSelf();
            this.ApplicationContainer = containerBuilder.Build();
            return(new AutofacServiceProvider(ApplicationContainer));
        }