예제 #1
0
 /// <summary>
 /// IoC初始化
 /// </summary>
 /// <param name="services"></param>
 /// <returns></returns>
 private IServiceProvider InitIoC(IServiceCollection services)
 {
     //services.UseOracle(Configuration);
     //services.UseMysql(Configuration);
     //services.UseSqlServer(Configuration);
     return(AspectCoreContainer.BuildServiceProvider(services));//接入AspectCore.Injector
 }
예제 #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider 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.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, option =>
            {
                option.LoginPath        = "/SignIn";
                option.AccessDeniedPath = "/Home/Error";
                option.Cookie.HttpOnly  = true;
            });

            services.Configure <DbContextOption>(Configuration.GetSection("ConnectionStrings"));

            //services.AddSingleton(Configuration);
            services.AddScopedAssembly("Agile.Repository");
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();//用于获取请求上下文
            services.AddMvc(option =>
            {
                option.Filters.Add(new GlobalExceptionFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            return(AspectCoreContainer.BuildServiceProvider(services));
        }
예제 #3
0
        public IServiceProvider BuildServiceForMongoDB()
        {
            IServiceCollection services = new ServiceCollection();

            //在这里注册EF上下文
            services = RegisterMongoDbContext(services);
            services.AddOptions();
            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
예제 #4
0
        /// <summary>
        /// IoC初始化
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private IServiceProvider InitIoC(IServiceCollection services)
        {
            services.AddOptions();
            services.AddMvc(option => { option.Filters.Add(new GlobalExceptionFilter()); })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddControllersAsServices();

            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
예제 #5
0
 public static IServiceProvider BuildAspectCoreServiceProvider(this IServiceCollection services,
                                                               Action <IAspectConfiguration> configure = null)
 {
     if (configure == null)
     {
         configure = config =>
         {
             config.Interceptors.AddTyped <FromDbContextFactoryInterceptor>();
         };
     }
     return(ServiceLocator.Current = AspectCoreContainer.BuildServiceProvider(services, configure));
 }
예제 #6
0
        public IServiceProvider BuildServiceForSqlServer()
        {
            IServiceCollection services = new ServiceCollection();

            //在这里注册EF上下文
            services = RegisterSqlServerContext(services);
            services.Configure <CodeGenerateOption>(options =>
            {
                options.ModelsNamespace        = "Models";
                options.IRepositoriesNamespace = "IRepository";
                options.RepositoriesNamespace  = "Repository";
                options.OutputPath             = "D:\\VSCode\\Demo\\AutoGenerateCode";
            });
            services.AddOptions();
            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
예제 #7
0
        public IServiceProvider BuildServiceForOracle()
        {
            IServiceCollection services = new ServiceCollection();

            services.Configure <CodeGenerateOption>(options =>
            {
                options.OutputPath             = "F:\\Test\\Oracle";
                options.ModelsNamespace        = "Zxw.Framework.UnitTest.Models";
                options.IRepositoriesNamespace = "Zxw.Framework.UnitTest.IRepositories";
                options.RepositoriesNamespace  = "Zxw.Framework.UnitTest.Repositories";
                options.ControllersNamespace   = "Zxw.Framework.UnitTest.Controllers";
            });
            //在这里注册EF上下文
            services = RegisterOracleDbContext(services);
            services.AddOptions();
            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
예제 #8
0
        public IServiceProvider BuildServiceForPostgreSql()
        {
            IServiceCollection services = new ServiceCollection();

            //在这里注册EF上下文
            services = RegisterPostgreSqlContext(services);
            services.Configure <CodeGenerateOption>(options =>
            {
                options.OutputPath             = "F:\\Test\\PostgreSQL";
                options.ModelsNamespace        = "Zxw.Framework.Website.Models";
                options.IRepositoriesNamespace = "Zxw.Framework.Website.IRepositories";
                options.RepositoriesNamespace  = "Zxw.Framework.Website.Repositories";
                options.ControllersNamespace   = "Zxw.Framework.Website.Controllers";
            });
            services.AddOptions();

            return(AspectCoreContainer.BuildServiceProvider(services, configure => configure.Interceptors.AddTyped <FromDbContextFactoryInterceptor>())); //接入AspectCore.Injector
        }
예제 #9
0
        public IServiceProvider BuildServiceForSqlServer()
        {
            IServiceCollection services = new ServiceCollection();

            //在这里注册EF上下文
            services = RegisterSqlServerContext(services);
            services.Configure <CodeGenerateOption>(options =>
            {
                options.ModelsNamespace        = "AeroIotPlatform.Models.Bridge";
                options.IRepositoriesNamespace = "AeroIotPlatform.IRepositories.Bridge";
                options.RepositoriesNamespace  = "AeroIotPlatform.Repositories.Bridge";
                options.ControllersNamespace   = "AeroIotPlatform.WebApi.Controllers";
                options.IServicesNamespace     = "AeroIotPlatform.IServices.Bridge";
                options.ServicesNamespace      = "AeroIotPlatform.Services.Bridge";
                options.OutputPath             = "E:\\CodeGenerator\\AeroIotPlatform\\Bridge";
            });
            services.AddOptions();
            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
예제 #10
0
        public IServiceProvider BuildServiceForSqlServer()
        {
            IServiceCollection services = new ServiceCollection();

            //在这里注册EF上下文
            services = RegisterSqlServerContext(services);
            services.Configure <CodeGenerateOption>(options =>
            {
                options.ModelsNamespace        = "Reach.AeroIOT.Models";
                options.IRepositoriesNamespace = "Reach.AeroIOT.IRepositories";
                options.RepositoriesNamespace  = "Reach.AeroIOT.Repositories";
                options.ControllersNamespace   = "Reach.AeroIOT.Controllers";
                options.OutputPath             = "E:\\CodeGenerator\\Reach.AeroIOT";
            });
            services.UseCsRedisClient(
                "127.0.0.1:6379,abortConnect=false,connectRetry=3,connectTimeout=3000,defaultDatabase=1,syncTimeout=3000,version=3.2.100,responseTimeout=3000");
            services.AddOptions();
            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
예제 #11
0
        private IServiceProvider InitIoC(IServiceCollection services)
        {
            #region Swagger
            // IoC - ISwaggerProvider
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc(Configuration["Service:Swagger:DocName"], new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Title       = Configuration["Service:Swagger:Title"],
                    Version     = Configuration["Service:Swagger:Version"],
                    Description = Configuration["Service:Swagger:Description"],
                    Contact     = new Swashbuckle.AspNetCore.Swagger.Contact
                    {
                        Name  = Configuration["Service:Swagger:Contacter"],
                        Email = Configuration["Service:Swagger:ContacterEmail"]
                    }
                });
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, Configuration["Service:Swagger:XmlFile"]);
                c.IncludeXmlComments(xmlPath);
            });
            #endregion

            #region Redis

            var redisConnectionString = Configuration.GetConnectionString("Redis");
            //启用Redis
            services.AddDistributedRedisCache(option =>
            {
                option.Configuration = redisConnectionString; //redis连接字符串
                option.InstanceName  = "mysites";             //Redis实例名称
            });
            //全局设置Redis缓存有效时间为5分钟。
            services.Configure <DistributedCacheEntryOptions>(option =>
                                                              option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));

            #endregion

            #region MemoryCache

            //启用MemoryCache
            services.AddMemoryCache();

            #endregion

            #region connectionstring
            var dbConnectionString = Configuration.GetConnectionString("DataBase");//连接字符串
            #endregion

            #region EFCodeFirst注入Database
            //配置DbContextOption
            //services.Configure<DbContextOption>(options =>
            //{
            //    options.ConnectionString = dbConnectionString;
            //    options.ModelAssemblyName = "MySites.DataModels";
            //});
            //var dataBaseType = Configuration.GetConnectionString("DataBaseType");//数据库类型
            //if (dataBaseType == "MsSqlServer")
            //{
            //    services.AddSingleton<IDbContextCore, SqlServerDbContext>();//注入EF上下文
            //}
            //else if (dataBaseType == "MySql")
            //{
            //    services.AddSingleton<IDbContextCore, MySqlDbContext>();//注入EF上下文
            //}
            //else
            //{
            //    throw new Exception("未能找到相应的数据库连接!");
            //}


            services.AddScoped <Chloe.IDbContext>((serviceProvider) =>
            {
                return(new Chloe.MySql.MySqlContext(new MySqlConnectionFactory(dbConnectionString)));
            });
            #endregion

            #region ChloeORM注入Database
            var dataBaseType = Configuration.GetConnectionString("DataBaseType");//数据库类型
            if (dataBaseType == "MySQL")
            {
                services.AddScoped <Chloe.IDbContext>((serviceProvider) =>
                {
                    return(new Chloe.MySql.MySqlContext(new MySqlConnectionFactory(dbConnectionString)));
                });
            }
            else if (dataBaseType == "PostgreSQL")
            {
                services.AddScoped <Chloe.IDbContext>((serviceProvider) =>
                {
                    return(new Chloe.PostgreSQL.PostgreSQLContext(new PostgreSqlConnectionFactory(dbConnectionString))
                    {
                        ConvertToLowercase = false
                    });
                });
            }
            else
            {
                throw new Exception("未能找到相应的数据库连接!");
            }
            #endregion

            #region 各种注入
            services.AddSingleton(Configuration)//注入Configuration,ConfigHelper要用
            .AddScopedAssembly("Identification.IRepositories", "Identification.Repositories")
            .AddScopedAssembly("Auth.IServices", "Auth.Services")
            ;
            #endregion

            services.AddOptions();

            return(AspectCoreContainer.BuildServiceProvider(services));//接入AspectCore.Injector
        }
예제 #12
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region 缓存

            services.AddMemoryCache();
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = Configuration["Redis:ConnectionString"];
                options.InstanceName  = Configuration["Redis:Instance"];
            });

            #endregion

            #region 注入Database

            var settings = Configuration.Get <CustomerSettings>();

            foreach (var dbSetting in settings.DatabaseSettings)
            {
                switch (dbSetting.DatabaseType)
                {
                case "Postgresql":
                    services.AddDbContext <IDbContextCore, ChainContext>(ServiceLifetime.Scoped);

                    services.Configure <DbContextOption>(option =>
                    {
                        option.IsCodeFirst       = dbSetting.IsCodeFirst;
                        option.ModelAssemblyName = dbSetting.ModelAssemblyName;
                        option.ConnectionString  = dbSetting.ConnectionString;
                        option.DatabaseType      = dbSetting.DatabaseType;
                    });
                    break;

                default:
                    throw new Exception("未能找到相应的数据库连接!");
                }
            }

            #endregion

            #region 其他注入

            services.AddSingleton(Configuration)
            .AddScopedAssembly("Explorer.Service.DataAccess.Interface",
                               "Explorer.Service.DataAccess.Implement");

            services.AddServiceModel();

            services.AddMvc()
            .AddControllersAsServices();

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                                         builder.SetIsOriginAllowed(origin => true).AllowAnyHeader().AllowAnyMethod()
                                         .AllowCredentials());
            });

            services.AddOptions();
            services.AddAspectCoreContainer();
            services.AddContractClient(Configuration);
            services.AddQuartz(Configuration);
            services.AddSignalR();

            #endregion

            return(AspectCoreContainer.BuildServiceProvider(services));
        }
        /// <summary>
        /// IoC初始化
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        private IServiceProvider InitIoC(IServiceCollection services)
        {
            //database connectionstring
            var dbConnectionString = Configuration.GetConnectionString("MsSqlServer");

            #region Redis

            var redisConnectionString = Configuration.GetConnectionString("Redis");
            //启用Redis
            services.AddDistributedRedisCache(option =>
            {
                option.Configuration = redisConnectionString; //redis连接字符串
                option.InstanceName  = "sample";              //Redis实例名称
            });
            //全局设置Redis缓存有效时间为5分钟。
            //services.Configure<DistributedCacheEntryOptions>(option =>
            //    option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));

            #endregion

            #region MemoryCache

            //启用MemoryCache
            services.AddMemoryCache();

            #endregion

            #region 配置DbContextOption

            //配置DbContextOption
            services.Configure <DbContextOption>(options =>
            {
                options.ConnectionString  = dbConnectionString;
                options.ModelAssemblyName = "Zxw.Framework.Website.Models";
            });

            #endregion

            #region 配置CodeGenerateOption

            //配置CodeGenerateOption
            services.Configure <CodeGenerateOption>(options =>
            {
                options.ModelsNamespace        = "Zxw.Framework.Website.Models";
                options.IRepositoriesNamespace = "Zxw.Framework.Website.IRepositories";
                options.RepositoriesNamespace  = "Zxw.Framework.Website.Repositories";
                options.ControllersNamespace   = "Zxw.Framework.Website.Controllers";
            });

            #endregion

            #region 各种注入

            services.AddSingleton(Configuration)                                                                //注入Configuration,ConfigHelper要用
            .AddScoped <IDbContextCore, SqlServerDbContext>()                                                   //注入EF上下文
            .AddTransientAssembly("Zxw.Framework.Website.IRepositories", "Zxw.Framework.Website.Repositories"); //注入仓储

            #endregion

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath  = "/Account/Index";
                options.LogoutPath = "/Account/Logout";
            });
            services.AddOptions();
            services.AddMvc(option =>
            {
                option.Filters.Add(new GlobalExceptionFilter());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddControllersAsServices();

            return(AspectCoreContainer.BuildServiceProvider(services));//接入AspectCore.Injector
        }
예제 #14
0
 /// <summary>
 /// 使用AspectCore注册服务
 /// </summary>
 /// <param name="services"></param>
 public IServiceProvider ConfigureServices(IServiceCollection services)
 {
     services.AddOFServices(Configuration);
     return(AspectCoreContainer.BuildServiceProvider(services));
 }
예제 #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region 缓存

            services.AddMemoryCache();
            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = Configuration["Redis:ConnectionString"]; //redis连接字符串
                options.InstanceName  = Configuration["Redis:Instance"];         //Redis实例名称
            });
            #endregion


            #region 注入Database

            var settings = Configuration.Get <CustomerSettings>();

            foreach (var dbSetting in settings.DatabaseSettings)
            {
                switch (dbSetting.DatabaseType)
                {
                case "MsSqlServer":
                    services.AddDbContext <IDbContextCore, SqlServerDbContext>(ServiceLifetime.Scoped);    //注入EF上下文
                    break;

                case "MySql":
                    services.AddDbContext <IDbContextCore, CoreServiceContext>(ServiceLifetime.Scoped);    //注入EF上下文
                    break;

                case "MongoDB":
                    services.AddScoped <IMongoDbContext, MongoDbContext>(p => new MongoDbContext(dbSetting));    //注入EF上下文
                    continue;

                case "ExchangeMongoDb":
                    services.AddScoped <ExchangeMongoDbContext>(p => new ExchangeMongoDbContext(dbSetting));    //注入EF上下文
                    continue;

                case "PanguMongoDbContext":
                    services.AddScoped <PanguMongoDbContext>(p => new PanguMongoDbContext(dbSetting));    //注入EF上下文
                    continue;

                default:
                    throw new Exception("未能找到相应的数据库连接!");
                }


                services.Configure <DbContextOption>(option =>
                {
                    option.IsCodeFirst       = dbSetting.IsCodeFirst;
                    option.ModelAssemblyName = dbSetting.ModelAssemblyName;
                    option.ConnectionString  = dbSetting.ConnectionString;
                    option.DatabaseType      = dbSetting.DatabaseType;
                });
            }

            #endregion

            #region Session

            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name     = "ms";
                options.IdleTimeout     = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
            });

            #endregion

            #region Authentication

            var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
            services.AddSingleton(policy);

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(o =>
            {
                Task RedirectFunc(RedirectContext <CookieAuthenticationOptions> ctx)
                {
                    ctx.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return(Task.FromResult(0));
                }

                o.Cookie.Name       = "ngk";
                o.SlidingExpiration = true;
                o.ExpireTimeSpan    = new TimeSpan(4, 0, 0);

                o.Events = new CookieAuthenticationEvents
                {
                    OnRedirectToLogin        = RedirectFunc,
                    OnRedirectToAccessDenied = RedirectFunc
                };
            });

            #endregion

            #region 其他注入

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <PrincipalUser>();
            //services.AddSingleton<IBusinessCacheManager, BusinessCacheManager>();
            services.AddSingleton <ICaptchaClient, TxCaptchaClient>();
            services.AddSingleton <SmsClient, YunPianSmsClient>();


            //注入合约相关实现
            services.AddScoped <ContractClientFactory>()
            .AddScopedAssembly("Contract.Interface", "Contract.Implement.Ngk");
            services.AddSingleton(Configuration)                                       //注入Configuration,ConfigHelper要用
            .AddScopedAssembly("Ngk.DataAccess.Interface", "Ngk.DataAccess.Implement") //注入服务
            .AddScopedAssembly("Ngk.Business.Interface", "Ngk.Business.Implement")     //注入服务
            ;                                                                          //注入服务
            services.AddMvc(
                options => { options.Filters.Add <ApiAuthorizeFilter>(); })
            .AddControllersAsServices()
            .AddJsonOptions(o =>
            {
                //                    o.SerializerSettings.Converters.Add(new UnixDateTimeConverter());
                //                    JsonConvert.DefaultSettings = () => o.SerializerSettings;
            });

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                                         builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
            });


            services.AddHttpClient();
            services.AddOptions();
            services.AddAspectCoreContainer();

            #endregion

            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
예제 #16
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //数据库配置
            services.Configure <DbOption>("Aju.Carefree", Configuration.GetSection("DbOption"));
            //Cookie
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
            });
            //services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            //    .AddCookie(options =>
            //    {
            //        options.LoginPath = "/Account/Index";
            //        options.LogoutPath = "/Account/Logout";
            //        options.ExpireTimeSpan = TimeSpan.FromMinutes(15);
            //    });
            //Session
            //services.AddSession(options =>
            //{
            //    options.IdleTimeout = TimeSpan.FromMinutes(15);
            //    options.Cookie.HttpOnly = true;
            //});
            // services.Add(ServiceDescriptor.Singleton<ICacheService, RedisCacheService>());

            //services.AddDistributedRedisCache(option =>
            //{
            //    option.Configuration = Configuration.GetSection("Cache")["ConnectionCacheStr"];
            //});



            services.AddSession();
            //CSRF
            services.AddAntiforgery(options =>
            {
                options.FormFieldName = "AntiforgeryKey_Aju";
                options.HeaderName    = "X-CSRF-TOKEN-Aju";
                options.SuppressXFrameOptionsHeader = false;
            });
            //mvc
            services.AddMvc(options =>
            {
                options.Filters.Add(new GlobalExceptionFilter());
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddControllersAsServices()
            .AddFluentValidation(fv =>
            {
                //去掉其他的验证,只使用FluentValidation的验证规则
                fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
            });
            //添加数据保护组件
            services.AddDataProtection();

            #region Redis
            var redisConnectionString = Configuration.GetConnectionString("Redis");
            //启用Redis
            services.UseCsRedisClient(redisConnectionString);
            //AspectCoreContainer.Resolve();

            //全局设置Redis缓存有效时间为5分钟。
            //services.Configure<DistributedCacheEntryOptions>(option =>
            //    option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));
            #endregion
            //AddMiniProfiler
            services.AddMiniProfiler(options =>
            {
                //设定弹出窗口的位置是左下角
                options.PopupRenderPosition = StackExchange.Profiling.RenderPosition.BottomLeft;
                //在弹出的明细窗口里会显式Time With Children这列。
                options.PopupShowTimeWithChildren = true;
            });

            //services.AddDistributedServiceStackRedisCache(options =>
            //{
            //    Configuration.GetSection("Cache").Bind(options);
            //});

            #region Autofac
            //var builder = new ContainerBuilder();//实例化 AutoFac  容器

            //var baseType = typeof(IDependency);
            //var assembly = Assembly.Load("Aju.Carefree.Services");
            //builder.RegisterAssemblyTypes(assembly)
            //                  .Where(m => baseType.IsAssignableFrom(m) && m != baseType)
            //                .AsImplementedInterfaces();

            //var assemblyR = Assembly.Load("Aju.Carefree.Repositories");
            //builder.RegisterAssemblyTypes(assemblyR)
            //                .Where(m => baseType.IsAssignableFrom(m) && m != baseType)
            //                .AsImplementedInterfaces();

            //builder.Populate(services);

            //var applicationContainer = builder.Build();

            //return new AutofacServiceProvider(applicationContainer);

            #endregion

            services.AddSingleton(Configuration)
            .AddScopedAssembly("Aju.Carefree.IRepositories", "Aju.Carefree.Repositories") //注入仓储
            .AddScopedAssembly("Aju.Carefree.IServices", "Aju.Carefree.Services");        //注入服务
            return(AspectCoreContainer.BuildServiceProvider(services));                   //接入AspectCore.Injector
        }
 /// <summary>
 /// IoC初始化.
 /// </summary>
 /// <param name="services">服务列表.</param>
 /// <returns>IServiceProvider.</returns>
 public static IServiceProvider InitIoC(this IServiceCollection services)
 {
     // 接入AspectCore.Injector
     return(AspectCoreContainer.BuildServiceProvider(services));
 }
예제 #18
0
        private IServiceProvider InitIoC(IServiceCollection services)
        {
            //database connectionstring


            #region Redis

            var redisConnectionString = Configuration.GetConnectionString("Redis");
            //启用Redis
            services.AddDistributedRedisCache(option =>
            {
                option.Configuration = redisConnectionString; //redis连接字符串
                option.InstanceName  = "sample";              //Redis实例名称
            });
            //全局设置Redis缓存有效时间为5分钟。
            //services.Configure<DistributedCacheEntryOptions>(option =>
            //    option.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5));

            #endregion

            #region MemoryCache

            //启用MemoryCache
            services.AddMemoryCache();

            #endregion

            #region 配置DbContextOption

            //database connectionstring
            var dbConnectionString = Configuration.GetConnectionString("DataBase");//连接字符串
            //配置DbContextOption
            services.Configure <DbContextOption>(options =>
            {
                options.ConnectionString  = dbConnectionString;
                options.ModelAssemblyName = "MySites.DataModels";
            });
            #endregion

            #region Database
            var dataBaseType = Configuration.GetConnectionString("DataBaseType");//数据库类型
            if (dataBaseType == "MsSqlServer")
            {
                services.AddSingleton <IDbContextCore, SqlServerDbContext>();//注入EF上下文
            }
            else if (dataBaseType == "MySql")
            {
                services.AddSingleton <IDbContextCore, MySqlDbContext>();//注入EF上下文
            }
            #endregion

            #region 各种注入

            services.AddSingleton(Configuration)                                 //注入Configuration,ConfigHelper要用
            .AddSingleton <IDbContextCore, SqlServerDbContext>()                 //注入EF上下文
            .AddScopedAssembly("MySites.IServices", "MySites.Services")          //注入服务
            .AddScopedAssembly("MySites.IRepositories", "MySites.Repositories"); //注入服务
            services.AddMvc(option =>
            {
                option.Filters.Add(new GlobalExceptionFilter());
            })
            .AddControllersAsServices();

            #endregion

            services.AddOptions();

            return(AspectCoreContainer.BuildServiceProvider(services));//接入AspectCore.Injector
        }
예제 #19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region 注入Database

            var settings = Configuration.Get <CustomerSettings>();

            foreach (var dbSetting in settings.DatabaseSettings)
            {
                switch (dbSetting.DatabaseType)
                {
                case "MsSqlServer":
                    services.AddDbContext <IDbContextCore, SqlServerDbContext>(ServiceLifetime.Scoped);    //注入EF上下文
                    break;

                case "MySql":
                    services.AddDbContext <IDbContextCore, CoreServiceContext>(ServiceLifetime.Scoped);    //注入EF上下文
                    break;

                case "MongoDB":
                    services.AddScoped <IMongoDbContext, MongoDbContext>(p => new MongoDbContext(dbSetting));    //注入EF上下文
                    continue;

                case "ExchangeMongoDb":
                    services.AddScoped <ExchangeMongoDbContext>(p => new ExchangeMongoDbContext(dbSetting));    //注入EF上下文
                    continue;

                default:
                    throw new Exception("未能找到相应的数据库连接!");
                }


                services.Configure <DbContextOption>(option =>
                {
                    option.IsCodeFirst       = dbSetting.IsCodeFirst;
                    option.ModelAssemblyName = dbSetting.ModelAssemblyName;
                    option.ConnectionString  = dbSetting.ConnectionString;
                    option.DatabaseType      = dbSetting.DatabaseType;
                });
            }

            #endregion

            #region Session

            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.Cookie.Name     = "ms";
                options.IdleTimeout     = TimeSpan.FromMinutes(30);
                options.Cookie.HttpOnly = true;
            });

            #endregion

            #region Authentication

            //var policy = new AuthorizationPolicyBuilder()
            //    .RequireAuthenticatedUser()
            //    .Build();
            //services.AddSingleton(policy);

            //// IdentityServer
            //services.AddAuthentication(Configuration["IdentityService:DefaultScheme"])
            //    .AddIdentityServerAuthentication(options =>
            //    {
            //        options.Authority = Configuration["IdentityService:Uri"];
            //        options.JwtValidationClockSkew = TimeSpan.FromSeconds(0);
            //        options.RequireHttpsMetadata = Convert.ToBoolean(Configuration["IdentityService:UseHttps"]);
            //    });

            #endregion

            #region 其他注入

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <PrincipalUser>();
            services.AddScoped <YunPianSmsClient>();
            //添加 YunPian 服务
            services.AddYunPianService(options =>
                                       options.ApiKey = Configuration["YunPianApiKey"]
                                       );
            services.AddSingleton <ICaptchaClient, TxCaptchaClient>();
            services.AddSingleton <IdentityServiceClient>();

            //注入合约相关实现
            services.AddScoped <ContractClientFactory>()
            .AddScopedAssembly("Contract.Interface", "Contract.Implement.Ngk");
            services.AddSingleton(Configuration)                                       //注入Configuration,ConfigHelper要用
            .AddScopedAssembly("Ngk.DataAccess.Interface", "Ngk.DataAccess.Implement") //注入服务
            .AddScopedAssembly("Ngk.Business.Interface", "Ngk.Business.Implement")     //注入服务
            ;                                                                          //注入服务

            services
            .AddMvc(options =>
            {
                //options.Filters.Add<ApiAuthorizeFilter>();
            })
            .AddControllersAsServices()
            .AddJsonOptions(o =>
            {
                //                    o.SerializerSettings.Converters.Add(new UnixDateTimeConverter());
                //                    JsonConvert.DefaultSettings = () => o.SerializerSettings;
            });

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                                         builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().AllowCredentials());
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("ngk",
                             new Info
                {
                    Title       = "Ngk Service API",
                    Version     = "v1.0",
                    Description =
                        "进行数据推送和修改的都采用POST,获取数据的都采用GET。POST推送时,通过Body传输Json数据;GET参数请通过url传值。所有返回都将采用Json数据格式。若为多语言请求,请在请求头里增加lang传值,目前包含语言头:zh、zh_tw、en、ja、ar、ko、fr、es、ru、pt、de"
                });

                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                var xmlPath  = Path.Combine(basePath, "Ngk.Service.xml");
                c.IncludeXmlComments(xmlPath, true);
                xmlPath = Path.Combine(basePath, "Ngk.DataAccess.DTO.xml");
                c.IncludeXmlComments(xmlPath, true);
            });

            services.AddHttpClient();
            services.AddOptions();
            services.AddAspectCoreContainer();
            services.AddConsulService();

            #endregion

            return(AspectCoreContainer.BuildServiceProvider(services)); //接入AspectCore.Injector
        }
 public static IServiceProvider BuildAspectCoreServiceProvider(this IServiceCollection services,
                                                               Action <IAspectConfiguration> configure = null)
 {
     return(ServiceLocator.Current = AspectCoreContainer.BuildServiceProvider(services, configure));
 }