public static void AddBrickPile(this IServiceCollection services)
        {
            _serviceProvider = services.BuildServiceProvider();

            services.AddMvc().ConfigureApplicationPartManager(manager =>
            {
                var feature = new ControllerFeature();
                manager.PopulateFeature(feature);
                services.AddSingleton<IControllerMapper>(new ControllerMapper(feature));
            });

            services.AddRouting(options =>
            {
                options.AppendTrailingSlash = true;
                options.LowercaseUrls = true;
            });

            services.Configure<MvcOptions>(options =>
            {
                options.ModelBinderProviders.Insert(0, new DefaultModelBinderProvider(DocumentStore));
                options.Filters.Add(typeof(PublishedFilterAttribute), 1);
                options.Filters.Add(typeof(AuthorizeFilterAttribute), 2);
            });

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton(DocumentStore);
            services.AddTransient<IRouteResolverTrie>(provider => new RouteResolverTrie(provider.GetService<IDocumentStore>()));
            services.AddTransient<IBricsContextAccessor>(provider => new BricsContextAccessor(provider.GetService<IHttpContextAccessor>(), provider.GetService<IDocumentStore>()));
        }
Example #2
0
 public AssemblyNode ReadApplicationPart(ApplicationPartManager applicationPartManager)
 {
     var feature = new ControllerFeature();
     applicationPartManager.PopulateFeature(feature);
     var converter = new Converter();
     var controllerTypes = feature.Controllers.Select(c => c.AsType());
     return ReadControllers(controllerTypes);
 }
 public ControllerMapper(ControllerFeature feature)
 {
     foreach (var type in feature.Controllers)
     {
         ControllerMap.TryAdd(type.GetType(), type.Name.Replace("Controller", ""));
         var methodNames = type.GetMethods().Select(x => x.Name).ToArray();
         ControllerActionMap.TryAdd(type.Name.Replace("Controller", ""), methodNames);
     }
 }
        /// <summary>
        /// Registers the ASP.NET Core MVC controller instances that are defined in the application through
        /// the <see cref="ApplicationPartManager"/>.
        /// </summary>
        /// <param name="container">The container the controllers should be registered in.</param>
        /// <param name="applicationBuilder">The ASP.NET object that holds the application's configuration.
        /// </param>
        public static void RegisterMvcControllers(this Container container,
            IApplicationBuilder applicationBuilder)
        {
            Requires.IsNotNull(container, nameof(container));
            Requires.IsNotNull(applicationBuilder, nameof(applicationBuilder));

            var manager = applicationBuilder.ApplicationServices.GetRequiredService<ApplicationPartManager>();

            var feature = new ControllerFeature();
            manager.PopulateFeature(feature);

            RegisterControllerTypes(container, feature.Controllers.Select(t => t.AsType()));
        }
        /// <summary>
        /// Registers discovered controllers as services in the <see cref="IServiceCollection"/>.
        /// </summary>
        /// <param name="builder">The <see cref="IMvcBuilder"/>.</param>
        /// <returns>The <see cref="IMvcBuilder"/>.</returns>
        public static IMvcBuilder AddControllersAsServices(this IMvcBuilder builder)
        {
            var feature = new ControllerFeature();
            builder.PartManager.PopulateFeature(feature);

            foreach (var controller in feature.Controllers.Select(c => c.AsType()))
            {
                builder.Services.TryAddTransient(controller, controller);
            }

            builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());

            return builder;
        }
Example #6
0
 public void PopulateFeature(IEnumerable <ApplicationPart> parts, ControllerFeature feature)
 {
     feature.Controllers.Add(Type.GetTypeInfo());
 }
Example #7
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //添加.net自带缓存
            services.AddMemoryCache();

            #region 注入获取HTTP上下文服务
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            #endregion

            #region 注入Node服务
            services.AddNodeServices(options => {
                var path                    = Directory.GetParent(Directory.GetCurrentDirectory());
                options.ProjectPath         = path + @"\NodeEncrpty";
                options.WatchFileExtensions = new[] { ".js", ".sass" };
            });
            #endregion

            #region 跨域
            var urls = Configuration["AppConfig:Cores"].Split(',');
            services.AddCors(options =>
                             options.AddPolicy("AllowSameDomain",
                                               builder => builder.WithOrigins(urls).AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials())
                             );
            #endregion

            #region API文档注入服务
            services.AddSwaggerGen(options => {
                options.SwaggerDoc("v1",
                                   new Info {
                    Title          = "CGT-Insure-Api",
                    Version        = "v1",
                    Description    = "A simple api to search using geo location in Elasticsearch",
                    TermsOfService = "None"
                }
                                   );

                var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "CGT.Api.Controllers.xml");
                options.IncludeXmlComments(filePath);

                var requestfilePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "CGT.Api.DTO.xml");
                options.IncludeXmlComments(requestfilePath);
                options.DescribeAllEnumsAsStrings();
            });
            #endregion

            #region MVC修改控制器描述
            services.AddHttpContextAccessor();
            services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>());
            services.AddMvc(config => {
                config.RespectBrowserAcceptHeader = true;
            })
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new ContractResolver())
            .AddJsonOptions(options => options.SerializerSettings.Converters.Add(new ChinaDateTimeConverter()))
            .AddFormatterMappings(options => options.SetMediaTypeMappingForFormat("xlsx", new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")))
            .AddFormatterMappings(options => options.SetMediaTypeMappingForFormat("jpeg", new MediaTypeHeaderValue("image/jpeg")))
            .AddFormatterMappings(options => options.SetMediaTypeMappingForFormat("jpg", new MediaTypeHeaderValue("image/jpeg")));

            #endregion

            #region Autofac配置
            var autofac  = new ContainerBuilder();
            var assembly = Assembly.Load(new AssemblyName("CGT.Api.Controllers"));
            var manager  = new ApplicationPartManager();

            manager.ApplicationParts.Add(new AssemblyPart(assembly));
            manager.FeatureProviders.Add(new ControllerFeatureProvider());

            var feature = new ControllerFeature();

            manager.PopulateFeature(feature);

            autofac.RegisterType <ApplicationPartManager>().AsSelf().SingleInstance();
            autofac.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired();

            autofac.RegisterModule(new AutofacModule());
            autofac.Populate(services);
            this.ApplicationContainer = autofac.Build();
            #endregion

            #region AutoMapper
            AutoMapperConfiguration.RegisterMappings();
            #endregion
            //设置支持gb2312
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            return(new AutofacServiceProvider(this.ApplicationContainer));
        }
        public static IServiceCollection AddFrameworkService(this IServiceCollection services,
                                                             Func <ActionExecutingContext, string> CsSector = null,
                                                             List <IDataPrivilege> dataPrivilegeSettings    = null,
                                                             WebHostBuilderContext webHostBuilderContext    = null
                                                             )
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();
            IConfigurationRoot config = null;

            var configBuilder =
                new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();

            if (webHostBuilderContext != null)
            {
                IHostingEnvironment env = webHostBuilderContext.HostingEnvironment;
                configBuilder
                .AddJsonFile(
                    $"appsettings.{env.EnvironmentName}.json",
                    optional: true,
                    reloadOnChange: true
                    );
            }
            config = configBuilder.Build();

            var gd = GetGlobalData();

            services.AddSingleton(gd);
            var con = config.Get <Configs>() ?? new Configs();

            if (dataPrivilegeSettings != null)
            {
                con.DataPrivilegeSettings = dataPrivilegeSettings;
            }
            else
            {
                con.DataPrivilegeSettings = new List <IDataPrivilege>();
            }
            services.AddSingleton(con);
            services.AddResponseCaching();
            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name = con.CookiePre + ".Session";
                options.IdleTimeout = TimeSpan.FromSeconds(3600);
            });
            SetupDFS(con);


            var mvc   = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.dll").FirstOrDefault();
            var admin = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.Admin.dll").FirstOrDefault();

            services.AddMvc(options =>
            {
                // ModelBinderProviders
                options.ModelBinderProviders.Insert(0, new StringBinderProvider());

                // Filters
                options.Filters.Add(new DataContextFilter(CsSector));
                options.Filters.Add(new PrivilegeFilter());
                options.Filters.Add(new FrameworkFilter());
            })
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

                // custom ContractResolver
                options.SerializerSettings.ContractResolver = new WTMContractResolver()
                {
                    //NamingStrategy = new CamelCaseNamingStrategy()
                };
            })
            .ConfigureApplicationPartManager(m =>
            {
                var feature = new ControllerFeature();
                m.ApplicationParts.Add(new AssemblyPart(mvc));
                if (admin != null)
                {
                    m.ApplicationParts.Add(new AssemblyPart(admin));
                }
                m.PopulateFeature(feature);
                services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter  = true;
                options.InvalidModelStateResponseFactory = (a) =>
                {
                    return(new BadRequestObjectResult(a.ModelState.GetErrorJson()));
                };
            });


            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.FileProviders.Add(
                    new EmbeddedFileProvider(
                        mvc,
                        "WalkingTec.Mvvm.Mvc" // your external assembly's base namespace
                        )
                    );
                if (admin != null)
                {
                    options.FileProviders.Add(
                        new EmbeddedFileProvider(
                            admin,
                            "WalkingTec.Mvvm.Mvc.Admin" // your external assembly's base namespace
                            )
                        );
                }
            });

            services.Configure <FormOptions>(y =>
            {
                y.ValueLengthLimit         = int.MaxValue;
                y.MultipartBodyLengthLimit = con.FileUploadOptions.UploadLimit;
            });

            services.AddSingleton <IUIService, DefaultUIService>();
            GlobalServices.SetServiceProvider(services.BuildServiceProvider());
            return(services);
        }
Example #9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            /*ef*/
            services.AddDbContext <EfDbContext>(option => option.UseLazyLoadingProxies().UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));//配置sqlserver
            //services.AddScoped<IUnitOfWork, UnitOfWork<EfDbContext>>();//注入UOW依赖,确保每次请求都是同一个对象
            //依赖注入 若出现重复注册的问题,请使用AddTransient
            //services.AddTransient<IDatabaseFactory, DatabaseFactory>();

            /*注入httpContext*/
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddSingleton <IConfigurationRoot>(Configuration);

            /*跨域访问*/

            #region 跨域

            var urls = Configuration.GetSection("CoresSettings:Urls").Value.Split(',');
            services.AddCors(options =>
                             options.AddPolicy("CoresDomain", blder =>
                                               blder.WithOrigins(urls)
                                               .AllowAnyMethod()
                                               .AllowAnyHeader()
                                               .AllowAnyOrigin()
                                               .AllowCredentials())
                             );

            #endregion 跨域

            //identityServer4
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = Configuration.GetSection("IdentityServerSettings:Authority").Value;
                options.RequireHttpsMetadata = false;
                options.ApiName = Configuration.GetSection("IdentityServerSettings:ApiName").Value;
            });

            /*https://www.cnblogs.com/daxnet/p/6181366.html*/
            //Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "Netcore.Api接口文档",
                    Description    = "RESTful API for Netcore.Api",
                    TermsOfService = "None",
                    Contact        = new Contact {
                        Name = "Alvin_Su", Email = "*****@*****.**", Url = ""
                    }
                });

                //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "WechatBusiness.Api.xml");
                c.IncludeXmlComments(xmlPath);
                c.DescribeAllEnumsAsStrings();
                c.IgnoreObsoleteActions();
                //identityServer4
                c.AddSecurityDefinition("oauth2", new OAuth2Scheme
                {
                    Type = "oauth2",
                    Flow = "password",
                    //AuthorizationUrl = "http://localhost:5006",
                    TokenUrl = string.Concat(Configuration.GetSection("IdentityServerSettings:Authority").Value.TrimEnd('/')
                                             , Configuration.GetSection("IdentityServerSettings:TokenUrl").Value),//  "http://auth.handnear.com/connect/token",
                    Scopes = new Dictionary <string, string>
                    {
                        { "Api", "secret" }
                    },
                });
                c.OperationFilter <HttpHeaderOperation>(); // 添加httpHeader参数
            });

            //Hangfire
            services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("DefaultConnection")));

            //Area
            var baseController     = typeof(BaseController);
            var controllerAssembly = baseController.GetTypeInfo().Assembly;
            services.AddMvc(options =>
            {
                //options.Filters.Add<ApiResourceFilter>();
                options.Filters.Add <ApiExceptionFilter>();
                options.Filters.Add <ApiActionFilter>();
                options.Filters.Add(new ApiAuthorizationFilter());

                //支持原始输入
                options.InputFormatters.Insert(0, new RawRequestBodyFormatter());

                //xml
                //options.ReturnHttpNotAcceptable = true;
                //options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
                //options.InputFormatters.Add(new XmlSerializerInputFormatter());
                //options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
                //options.Conventions.Add(new CommandParameterBindingConvention());
            }).ConfigureApplicationPartManager(m =>
            {
                var feature = new ControllerFeature();
                m.ApplicationParts.Add(new AssemblyPart(controllerAssembly));
                m.PopulateFeature(feature);
                services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
            }).AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
                //默认返回json为小写,设置后不会变换model字段的大小写
                options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //automapper
            services.AddAutoMapper(typeof(IProfile));

            //redis
            var redisAppSet = Configuration.GetSection("RedisSettings").Get <RedisSettings>();
            if (redisAppSet.IsEnabled)
            {
                var redisOption = new RedisCacheOptions()
                {
                    Configuration = redisAppSet.Connection,
                    InstanceName  = redisAppSet.InstanceName
                };
                services.AddSingleton <ICacheHelper>(new RedisCacheHelper(redisOption, redisAppSet.Database ?? 0));
            }
            else//MemoryCache
            {
                services.AddSingleton <ICacheHelper>(new MemoryCacheHelper(new MemoryCacheOptions()));
            }

            //RabbitMQ
            var rabbitMQAppSet = Configuration.GetSection("RabbitMQSettings").Get <RabbitMQSetting>();
            if (rabbitMQAppSet.IsEnabled)
            {
                services.AddSingleton(new RabbitMQHelper(rabbitMQAppSet));
            }


            //autofac
            var builder = new ContainerBuilder();

            //builder.RegisterType<AccountService>().As<IAccountService>();
            //builder.RegisterGeneric(typeof(EfRepositoryBase<>)).As(typeof(IRepository<>)).InstancePerDependency();//注册仓储泛型
            builder.Populate(services);
            var module = new ConfigurationModule(Configuration);
            builder.Register(c => new AopInterceptor());
            builder.RegisterModule(module);
            this.Container = builder.Build();

            //FluentScheduler  --Hangfire
            JobManager.Initialize(new TaskBaseRegistry());
            JobManager.Stop();

            return(new AutofacServiceProvider(this.Container));;
        }
        public void PopulateFeature(ApplicationPart parts, ControllerFeature feature)
        {
            var type = parts.Types.Where(f => f.Name == nameof(TestService)).FirstOrDefault();

            feature.Controllers.Add(type);
        }
Example #11
0
 /// <summary>
 /// Registers the closed generic controller for lobby requests.
 /// </summary>
 /// <param name="parts"></param>
 /// <param name="feature"></param>
 public void PopulateFeature(IEnumerable <ApplicationPart> parts, ControllerFeature feature)
 {
     feature.Controllers.Add(typeof(RegisterLobbyRequestController <TLobbyConnectionDetailsType, TLobbyDetailsType>).GetTypeInfo());
     feature.Controllers.Add(typeof(HelloRequestController <TLobbyConnectionDetailsType, TLobbyDetailsType>).GetTypeInfo());
 }
Example #12
0
        public static IServiceCollection AddFrameworkService(this IServiceCollection services,
                                                             Func <ActionExecutingContext, string> CsSector = null,
                                                             List <IDataPrivilege> dataPrivilegeSettings    = null,
                                                             WebHostBuilderContext webHostBuilderContext    = null
                                                             )
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            var configBuilder = new ConfigurationBuilder();

            if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json")))
            {
                var binLocation = Assembly.GetEntryAssembly()?.Location;
                if (!string.IsNullOrEmpty(binLocation))
                {
                    var binPath = new FileInfo(binLocation).Directory?.FullName;
                    if (File.Exists(Path.Combine(binPath, "appsettings.json")))
                    {
                        Directory.SetCurrentDirectory(binPath);
                        configBuilder.SetBasePath(binPath)
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .AddEnvironmentVariables();
                    }
                }
            }
            else
            {
                configBuilder.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();
            }

            if (webHostBuilderContext != null)
            {
                var env = webHostBuilderContext.HostingEnvironment;
                configBuilder
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
            }
            var config = configBuilder.Build();

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

            services.AddSingleton(gd);
            var con = config.Get <Configs>() ?? new Configs();

            if (dataPrivilegeSettings != null)
            {
                con.DataPrivilegeSettings = dataPrivilegeSettings;
            }
            else
            {
                con.DataPrivilegeSettings = new List <IDataPrivilege>();
            }
            services.AddSingleton(con);
            services.AddResponseCaching();
            services.AddMemoryCache();
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name = con.CookiePre + ".Session";
                options.IdleTimeout = TimeSpan.FromSeconds(3600);
            });
            SetupDFS(con);

            services.AddCors(options =>
            {
                if (con.CorsOptions?.Policy?.Count > 0)
                {
                    foreach (var item in con.CorsOptions.Policy)
                    {
                        string[] domains = item.Domain?.Split(',');
                        options.AddPolicy(item.Name,
                                          builder =>
                        {
                            builder.WithOrigins(domains)
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                        });
                    }
                }
                else
                {
                    options.AddPolicy("_donotusedefault",
                                      builder =>
                    {
                        builder.WithOrigins("http://localhost",
                                            "https://localhost")
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                    });
                }
            });


            // edit start by @vito
            services.TryAdd(ServiceDescriptor.Transient <IAuthorizationService, WTMAuthorizationService>());
            services.TryAdd(ServiceDescriptor.Transient <IPolicyEvaluator, Core.Auth.PolicyEvaluator>());
            services.TryAddEnumerable(
                ServiceDescriptor.Transient <IApplicationModelProvider, Core.Auth.AuthorizationApplicationModelProvider>());
            // edit end

            var mvc   = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.dll").FirstOrDefault();
            var admin = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Mvc.Admin.dll").FirstOrDefault();

            //set Core's _Callerlocalizer to use localizer point to the EntryAssembly's Program class
            var programType      = Assembly.GetEntryAssembly().GetTypes().Where(x => x.Name == "Program").FirstOrDefault();
            var coredll          = gd.AllAssembly.Where(x => x.ManifestModule.Name == "WalkingTec.Mvvm.Core.dll").FirstOrDefault();
            var programLocalizer = new ResourceManagerStringLocalizerFactory(
                Options.Create(
                    new LocalizationOptions
            {
                ResourcesPath = "Resources"
            })
                , new Microsoft.Extensions.Logging.LoggerFactory()
                )
                                   .Create(programType);

            coredll.GetType("WalkingTec.Mvvm.Core.Program").GetProperty("_Callerlocalizer").SetValue(null, programLocalizer);


            services.AddMvc(options =>
            {
                // ModelBinderProviders
                options.ModelBinderProviders.Insert(0, new StringBinderProvider());

                // Filters
                options.Filters.Add(new AuthorizeFilter());
                options.Filters.Add(new DataContextFilter(CsSector));
                options.Filters.Add(new PrivilegeFilter());
                options.Filters.Add(new FrameworkFilter());
            })
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

                // custom ContractResolver
                options.SerializerSettings.ContractResolver = new WTMContractResolver()
                {
                    //NamingStrategy = new CamelCaseNamingStrategy()
                };
            })
            .ConfigureApplicationPartManager(m =>
            {
                var feature = new ControllerFeature();
                if (mvc != null)
                {
                    m.ApplicationParts.Add(new AssemblyPart(mvc));
                }
                if (admin != null)
                {
                    m.ApplicationParts.Add(new AssemblyPart(admin));
                }
                m.PopulateFeature(feature);
                services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
            })
            .AddControllersAsServices()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .ConfigureApiBehaviorOptions(options =>
            {
                options.SuppressModelStateInvalidFilter  = true;
                options.InvalidModelStateResponseFactory = (a) =>
                {
                    return(new BadRequestObjectResult(a.ModelState.GetErrorJson()));
                };
            })
            .AddDataAnnotationsLocalization(options =>
            {
                var coreType = coredll?.GetTypes().Where(x => x.Name == "Program").FirstOrDefault();
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    if (Core.Program.Buildindll.Any(x => type.FullName.StartsWith(x)))
                    {
                        var rv = factory.Create(coreType);
                        return(rv);
                    }
                    else
                    {
                        return(factory.Create(programType));
                    }
                };
            })
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);


            services.Configure <RazorViewEngineOptions>(options =>
            {
                if (mvc != null)
                {
                    options.FileProviders.Add(
                        new EmbeddedFileProvider(
                            mvc,
                            "WalkingTec.Mvvm.Mvc" // your external assembly's base namespace
                            )
                        );
                }
                if (admin != null)
                {
                    options.FileProviders.Add(
                        new EmbeddedFileProvider(
                            admin,
                            "WalkingTec.Mvvm.Mvc.Admin" // your external assembly's base namespace
                            )
                        );
                }
            });

            services.Configure <FormOptions>(y =>
            {
                y.ValueLengthLimit         = int.MaxValue;
                y.MultipartBodyLengthLimit = con.FileUploadOptions.UploadLimit;
            });

            services.AddSingleton <IUIService, DefaultUIService>();

            #region CookieWithJwtAuth

            // services.AddSingleton<UserStore>();
            services.AddSingleton <ITokenService, TokenService>();

            var jwtOptions = config.GetSection("JwtOptions").Get <JwtOptions>();
            if (jwtOptions == null)
            {
                jwtOptions = new JwtOptions();
            }
            services.Configure <JwtOptions>(config.GetSection("JwtOptions"));

            var cookieOptions = config.GetSection("CookieOptions").Get <Core.Auth.CookieOptions>();
            if (cookieOptions == null)
            {
                cookieOptions = new Core.Auth.CookieOptions();
            }

            services.Configure <Core.Auth.CookieOptions>(config.GetSection("CookieOptions"));

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.Configure <Core.Auth.CookieOptions>("", options =>
            {
            });
            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Cookie.Name     = CookieAuthenticationDefaults.CookiePrefix + AuthConstants.CookieAuthName;
                options.Cookie.HttpOnly = true;
                options.Cookie.SameSite = SameSiteMode.Strict;

                options.ClaimsIssuer      = cookieOptions.Issuer;
                options.SlidingExpiration = cookieOptions.SlidingExpiration;
                options.ExpireTimeSpan    = TimeSpan.FromSeconds(cookieOptions.Expires);
                // options.SessionStore = new MemoryTicketStore();

                options.LoginPath          = cookieOptions.LoginPath;
                options.LogoutPath         = cookieOptions.LogoutPath;
                options.ReturnUrlParameter = cookieOptions.ReturnUrlParameter;
                options.AccessDeniedPath   = cookieOptions.AccessDeniedPath;
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = AuthConstants.JwtClaimTypes.Name,
                    RoleClaimType = AuthConstants.JwtClaimTypes.Role,

                    ValidateIssuer = true,
                    ValidIssuer    = jwtOptions.Issuer,

                    ValidateAudience = true,
                    ValidAudience    = jwtOptions.Audience,

                    ValidateIssuerSigningKey = false,
                    IssuerSigningKey         = jwtOptions.SymmetricSecurityKey,

                    ValidateLifetime = true
                };
            });
            #endregion

            GlobalServices.SetServiceProvider(services.BuildServiceProvider());
            return(services);
        }
        public void PopulateFeature(AssemblyName assemblyName, IEnumerable <ApplicationPart> parts, ControllerFeature feature)
        {
            //var asse = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(x => x.Name.Contains("Common")).First();

            //var currentAssembly = Assembly.Load(asse);

            var currentAssembly = Assembly.Load(assemblyName);
            var candidates      = currentAssembly.GetExportedTypes().Where(x => x.GetCustomAttributes <GeneratedControllerAttribute>().Any());

            foreach (var candidate in candidates)
            {
                feature.Controllers.Add(
                    typeof(BaseController <>).MakeGenericType(candidate).GetTypeInfo()
                    );
            }
        }
Example #14
0
        public Task StartAsync(CancellationToken cancellationToken)
        {
            // Get the names of all the application parts. This is the short assembly name for AssemblyParts
            var applicationPartNames = _partManager.ApplicationParts.Select(x => x.Name).ToList();

            // Create a controller feature, and populate it from the application parts
            var controllerFeature = new ControllerFeature();

            _partManager.PopulateFeature(controllerFeature);

            // Get the names of all of the controllers
            var controllerNames = controllerFeature.Controllers.Select(x => x.Name).ToList();

            // Create a view feature, and populate it from the application parts
            var viewComponentFeatures = new ViewComponentFeature();

            _partManager.PopulateFeature(viewComponentFeatures);

            // Get the names of all of the view components
            var viewComponentNames = viewComponentFeatures.ViewComponents.Select(x => x.Name).ToList();

            // Create a razor views feature, and populate it from the application parts
            var razorViewFeatures = new ViewsFeature();

            _partManager.PopulateFeature(razorViewFeatures);

            // Get the names of all of the razor views
            var razorViewsNames = razorViewFeatures.ViewDescriptors.Select(x => x.RelativePath).ToList();

            // Create a view feature, and populate it from the application parts
            var tagHelperFeatures = new TagHelperFeature();

            _partManager.PopulateFeature(tagHelperFeatures);

            // Get the names of all of the views
            var tagHelperNames = tagHelperFeatures.TagHelpers.Select(x => x.Name).ToList();

            // Log the controllers
            if (applicationPartNames.Any())
            {
                _logger.LogInformation($"Found the following application parts: '{string.Join(", ", applicationPartNames)}'");
            }

            // Log the controllers
            if (controllerNames.Any())
            {
                _logger.LogInformation($"Found the following controllers: '{string.Join(", ", controllerNames)}'");
            }

            // Log the controllers
            if (viewComponentNames.Any())
            {
                _logger.LogInformation($"Found the following view components: '{string.Join(", ", viewComponentNames)}'");
            }

            // Log the razor views
            if (razorViewsNames.Any())
            {
                _logger.LogInformation($"Found the following razor views: '{string.Join(", ", razorViewsNames)}'");
            }

            // Log the tag helpers
            if (tagHelperNames.Any())
            {
                _logger.LogInformation($"Found the following tag helpers: '{string.Join(", ", tagHelperNames)}'");
            }

            return(Task.CompletedTask);
        }
Example #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            GlobalHostingEnvironment.HostingEnvironment = this.HostingEnvironment;
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            // Add framework services.
            services.Replace(ServiceDescriptor.Transient <IControllerActivator, ServiceBasedControllerActivator>());
            services.AddAuthorization(authorization =>
            {
                authorization.AddPolicy("EnterSystem", policy => policy.Requirements.Add(new EnterSystemRequirement()));
            });
            services.AddSession(session =>
            {
                session.IdleTimeout = TimeSpan.FromMinutes(30);
            });
            services.AddTimedJob();
            services.AddMvc(option =>
            {
                option.Filters.Add(new HandleErrorToLogAttribute());
            }).AddJsonOptions(option => {
                option.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm";
            });

            var assembly = this.GetType().GetTypeInfo().Assembly;
            var builder  = new ContainerBuilder();
            var manager  = new ApplicationPartManager();
            var feature  = new ControllerFeature();

            manager.ApplicationParts.Add(new AssemblyPart(assembly));
            manager.FeatureProviders.Add(new ControllerFeatureProvider());
            manager.PopulateFeature(feature);

            builder.RegisterTypes(feature.Controllers.Select(controller => controller.AsType()).ToArray()).PropertiesAutowired();
            builder.Register(c => new DbService(Configuration.GetSection("ConnectionStrings")["DefaultConnection"])).AsSelf().PropertiesAutowired();

            string[] assembliesName = { "SexyColor.BusinessComponents", "SexyColor.CommonComponents" };
            var      assemblies     = assembliesName.Select(w => Assembly.Load(new AssemblyName(w))).ToArray();


            //仓储批量注册
            builder.RegisterAssemblyTypes(assemblies).Where(t => t.Name.EndsWith("Repository")).AsSelf().AsImplementedInterfaces().SingleInstance().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

            //服务批量注册
            builder.RegisterAssemblyTypes(assemblies).Where(t => t.Name.EndsWith("Service")).AsSelf().AsImplementedInterfaces().SingleInstance().PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);

            //业务组件注册
            builder.Register(c => new AuthorizerHelper()).AsSelf().SingleInstance().PropertiesAutowired();
            builder.Register(c => new DefaultIdGenerator()).As <IdGenerator>().SingleInstance();
            builder.Register(c => new DefaultUserIdToUserNameDictionary()).As <UserIdToUserNameDictionary>().SingleInstance().PropertiesAutowired();
            builder.Register(c => new DefaultCaptchaManager()).As <ICaptchaManager>().SingleInstance();
            //builder.Register(c => new DefaultCacheService(new RedisMemoryCache(), new RuntimeMemoryCache(), 1.0F, true)).As<ICacheService>().SingleInstance();
            builder.Register(c => new DefaultCacheService(new RuntimeMemoryCache(), 1.0F)).As <ICacheService>().SingleInstance();
            builder.Register(c => new DefaultStorageService()).As <IStorageService>().SingleInstance();
            builder.Register(c => new DefaultStoreProvider(@"~/images")).As <IStoreProvider>().SingleInstance();
            builder.Register(c => new Logger(this.HostingEnvironment)).As <SexyColor.CommonComponents.ILogger>().SingleInstance();
            builder.Register(c => new Log4NetLoggerFactoryAdapter(repository.Name)).As <ILoggerFactoryAdapter>().SingleInstance();
            builder.Register(c => new QuartzTaskScheduler()).As <ITaskScheduler>().SingleInstance();
            //泛型注册
            builder.RegisterGeneric(typeof(Repository <>)).As(typeof(IRepository <>)).SingleInstance().PropertiesAutowired();

            builder.Populate(services);
            this.ApplicationContainer = builder.Build();
            BuilderContext.Register(services, Configuration);

            LogoSettings.RegisterSettings(LogoConfigManager.Instance().GetAllLogoConfigs());
            new DefaultResourceManager().Excute();
            ReadConfigurationHelper.Configuration = Configuration;
            DIContainer.RegisterContainer(this.ApplicationContainer);
            return(new AutofacServiceProvider(this.ApplicationContainer));
        }
Example #16
0
        public static IServiceCollection AddFrameworkService(this IServiceCollection services,
                                                             WebHostBuilderContext webHostBuilderContext = null
                                                             )
        {
            CurrentDirectoryHelpers.SetCurrentDirectory();

            var configBuilder = new ConfigurationBuilder();

            if (!File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json")))
            {
                var binLocation = Assembly.GetEntryAssembly()?.Location;
                if (!string.IsNullOrEmpty(binLocation))
                {
                    var binPath = new FileInfo(binLocation).Directory?.FullName;
                    if (File.Exists(Path.Combine(binPath, "appsettings.json")))
                    {
                        Directory.SetCurrentDirectory(binPath);
                        configBuilder.SetBasePath(binPath)
                        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                        .AddEnvironmentVariables();
                    }
                }
            }
            else
            {
                configBuilder.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                .AddEnvironmentVariables();
            }

            if (webHostBuilderContext != null)
            {
                var env = webHostBuilderContext.HostingEnvironment;
                configBuilder
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
            }

            var config = configBuilder.Build();

            new AppSettingProvider().Initial(config);//添加静态的配置全局配置文件

            var gd = AssemblyHelper.GetGlobalData();

            var currentNamespace = MethodBase.GetCurrentMethod().DeclaringType.Namespace;
            //获取标准类库的Assembly
            var currentAssembly = gd.AllAssembly.Where(x => x.ManifestModule.Name == $"{currentNamespace}.dll").FirstOrDefault();

            StackTrace ss = new StackTrace(true);
            MethodBase mb = ss.GetFrame(ss.FrameCount - 1).GetMethod();

            var userNamespace = mb.DeclaringType.Namespace;//调用标准版项目的定制版项目命名空间

            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
            });

            services.AddRazorPages()//添加RazorPages
            .AddRazorRuntimeCompilation()
            .ConfigureApplicationPartManager(m =>
            {
                //将标准类库的Controllers添加到定制版,即我们要运行的网站中
                var feature = new ControllerFeature();

                if (currentAssembly != null)
                {
                    m.ApplicationParts.Add(new AssemblyPart(currentAssembly));
                }
                m.PopulateFeature(feature);
                services.AddSingleton(feature.Controllers.Select(t => t.AsType()).ToArray());
            })
            .AddControllersAsServices()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix);//添加多语言支持

            //services.Configure<MvcRazorRuntimeCompilationOptions>(options =>
            //{
            //    if (currentAssembly != null)
            //    {
            //        options.FileProviders.Add(
            //        new EmbeddedFileProvider(
            //            currentAssembly,
            //            currentNamespace // your external assembly's base namespace
            //        )
            //    );
            //    }
            //});
            services.AddSingleton <ILoginUserService, LoginUserService>();//添加需要引用的其他服务

            services.AddMvc(options =>
            {
                options.Conventions.Add(new ApiControllerVersionConvention());//添加版本控制时忽略添加的某些重要属性
            });

            services.AddApiVersioning(o => {
                o.ReportApiVersions = true;//返回版本可使用的版本
                //o.ApiVersionReader = new UrlSegmentApiVersionReader();
                //o.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version"), new QueryStringApiVersionReader("api-version"));
                //o.ApiVersionReader = ApiVersionReader.Combine(new QueryStringApiVersionReader("api-version"));
                o.ApiVersionReader = ApiVersionReader.Combine(new HeaderApiVersionReader("api-version")); //版本号以什么形式,什么字段传递
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion  = new ApiVersion(1, 0);                                              //默认版本号
                o.ApiVersionSelector = new CurrentImplementationApiVersionSelector(o);                    //默认以当前最高版本进行访问
            });

            return(services);
        }
        private IEnumerable<TypeInfo> GetControllerTypes()
        {
            var feature = new ControllerFeature();
            _partManager.PopulateFeature(feature);

            return feature.Controllers;
        }
        public void PopulateFeature(IEnumerable <ApplicationPart> parts, ControllerFeature feature)
        {
            var controllerType = typeof(ClientController <T>).GetTypeInfo();

            feature.Controllers.Add(controllerType);
        }
Example #19
0
        protected override void Load(ContainerBuilder containerBuilder)
        {
            ApplicationPartManager manager = new ApplicationPartManager();
            Assembly assembly = this.GetType().GetTypeInfo().Assembly;

            manager.ApplicationParts.Add(new AssemblyPart(assembly));
            manager.FeatureProviders.Add(new ControllerFeatureProvider());
            var feature = new ControllerFeature();

            manager.PopulateFeature(feature);

            ContainerBuilder builder = new ContainerBuilder();

            builder.RegisterType <ApplicationPartManager>().AsSelf().SingleInstance();//单例
            builder.RegisterTypes(feature.Controllers.Select(ti => ti.AsType()).ToArray()).PropertiesAutowired();


            #region 业务的注入
            containerBuilder.Register(c => new CustomAutofacAop());                      //aop注册
            containerBuilder.RegisterType <A>().As <IA>().EnableInterfaceInterceptors(); //AOP
            // Microsoft.DotNet.PlatformAbstractions 是单独的nuget包
            var basePath = ApplicationEnvironment.ApplicationBasePath;

            //1-先注册sqlsuger,在 方法    services.DbInitialization(_configuration); 中已经注册
            //2- 再注册仓储Repository
            #region 泛型注入,没能实现,泛型的仓储接口 → 泛型的仓储实现
            // Type ty = assemblysRepository.GetTypes().FirstOrDefault();
            //   containerBuilder.RegisterGeneric(ty).As(typeof(IBaseRepository<>))
            //   .InstancePerDependency();//注册仓储泛型


            //containerBuilder.RegisterType<SqlSugerHelper<zCustomUserRoles>>().As<IBaseRepository<zCustomUserRoles>>();
            //containerBuilder.RegisterType<SqlSugerHelper<zCustomUser>>().As<IBaseRepository<zCustomUser>>();
            // 因为 完全解耦了,SqlSugerHelper这个是仓储管理员的具体实现-是泛型类
            // 在这里是不能访问 SqlSugerHelper 他的
            // 为了实现这两句代码,只能再创建“具体”的仓储管理员,才能实现,
            //

            #endregion

            var repositoryDllFile   = Path.Combine(basePath, "QinRepository.dll");
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            containerBuilder.RegisterAssemblyTypes(assemblysRepository)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();;

            //3-再注入服务
            var servicesDllFile   = Path.Combine(basePath, "QinServices.dll");
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            containerBuilder.RegisterAssemblyTypes(assemblysServices)
            .AsImplementedInterfaces()
            .InstancePerLifetimeScope();

            {
                //之前的写法
                //containerBuilder.RegisterType<zCustomUserRolesService>().As<IzCustomUserRolesService>();
                //containerBuilder.RegisterType<zCustomUserService>().As<IzCustomUserService>();
            }


            /*
             *  这样弄彻底解耦项目,直接加载dll文件,如果你新建一个table,你要建立这些类
             *  TableEntity(实体)→
             *  ItableRepository(接口)→tableRepository(实现类)→
             *  ItableService(接口)→tableService(实现类)
             *  总共3个接口,2个类
             *
             */

            #endregion

            #region 注入当前程序集的
            string text    = File.ReadAllText("BuilderExtend/InjectionBusinessServer.json");
            var    jobject = JObject.Parse(text);
            if (jobject == null || jobject.Count == 0)
            {
                return;
            }
            foreach (var item in jobject["Example"])
            {
                string name = ((JProperty)item).Name;
                Type   tt   = Type.GetType(name, true, true);
                containerBuilder.Register(c => tt);
            }
            foreach (var item in jobject["InterExample"])
            {
                string abstractname    = ((JProperty)item).Name;
                string Realizationname = ((JProperty)item).Value.ToString();
                Type   tt = Type.GetType(abstractname, true, true);
                Type   aa = Type.GetType(Realizationname, true, true);
                containerBuilder.RegisterType(tt).As(aa);
            }
            #endregion

            containerBuilder.Register(p => new MessageModel()).AsSelf().SingleInstance();
        }
Example #20
0
 public void PopulateFeature(IEnumerable <ApplicationPart> parts, ControllerFeature feature)
 {
     feature.Controllers.Add(typeof(StateMachineController <TKey, TSubject>).GetTypeInfo());
 }