// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <MapperService>(); services.AddTransient <Service_xuangubao>(); services.AddTransient <DBService>(); services.AddHttpClient(); services.AddSingleton <IRedisService, RedisService>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddCors(options => { options.AddPolicy("any123", builder => { #if DEBUG builder.WithOrigins(new string[] { "http://localhost:9000", }) #elif RELEASE builder.WithOrigins(new string[] { "http://fweb.gk2823.com" }) #endif //.AllowAnyMethod() //.AllowAnyHeader() //.AllowCredentials() .SetPreflightMaxAge(TimeSpan.FromSeconds(3600)) .WithHeaders("Authorization", "Content-Type", "Access-Control-Allow-Origin") //.WithMethods("GET", "POST", "OPTIONS"); .WithMethods("POST"); }); }); AutofacContainer.Build(services); }
public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton <MapperService>(); services.AddSingleton <AccountService>(); services.AddSingleton <H3CService>(); services.AddSingleton <DBService>(); services.AddHttpClient(); services.AddSingleton <IRedisService, RedisService>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); #if DEBUG //services.AddHostedService<DevService>(); #endif services.AddCors(options => { options.AddPolicy("fweb", builder => { #if DEBUG builder.WithOrigins(new string[] { "http://localhost:9004", }) #elif RELEASE builder.WithOrigins(new string[] { "http://admin.gk2823.com" }) #endif .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials() .SetPreflightMaxAge(TimeSpan.FromSeconds(3600)) .WithHeaders("Authorization", "Content-Type", "Access-Control-Allow-Origin", "refresh_token") .WithMethods("GET", "POST", "OPTIONS"); }); }); AutofacContainer.Build(services); }
// This method gets called by the runtime. Use this method to add services to the container. public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins(this.Configuration.GetSection("CorsIp")["IpAddress"]) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.Configure <ForwardedHeadersOptions>(options => { options.KnownProxies.Add(IPAddress.Parse("10.0.0.100")); }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //add swagger services.AddSwaggerGen(gen => { gen.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); //add log services.AddLogging(); services.AddTimedJob(); services.Configure <IoTHubAppSetting>(this.Configuration.GetSection("IoTHubAppSetting")); //add dependency injection IocContainer autofac = new AutofacContainer(services); return(autofac.Build().FetchServiceProvider()); }
/// <summary> /// 初始化Ioc容器 /// </summary> /// <param name="services"></param> /// <returns></returns> private IServiceProvider InitIoc(IServiceCollection services) { var connectionString = Configuration.GetConnectionString("MsSqlServer"); //var connectionString = Configuration.GetConnectionString("MySql"); var dbContextOption = new DbContextOption { ConnectionString = connectionString, DbType = DbTypeEnum.MSSQLSERVER, //DbType = DbTypeEnum.MYSQL, ModelAssemblyName = "Ses.AspNetCore.Entities", }; //var codeGenerateOption = new CodeGenerateOption //{ // ModelsNamespace = "Zxw.Framework.Website.Models", // IRepositoriesNamespace = "Zxw.Framework.Website.IRepositories", // RepositoriesNamespace = "Zxw.Framework.Website.Repositories", // IServicsNamespace = "Zxw.Framework.Website.IServices", // ServicesNamespace = "Zxw.Framework.Website.Services" //}; AutofacContainer.Register(Configuration); //注册配置 AutofacContainer.Register(dbContextOption); //注册数据库配置信息 //AutofacContainer.Register(codeGenerateOption);//注册代码生成器相关配置信息 AutofacContainer.Register(typeof(DefaultDbContext)); //注册EF上下文 AutofacContainer.RegisterGeneric(typeof(IRepository <,>), typeof(BaseRepository <,>)); AutofacContainer.RegisterGeneric(typeof(IBaseService <,>), typeof(BaseService <,>)); AutofacContainer.Register("Ses.AspNetCore.Services", "Ses.AspNetCore.IServices");//注册service return(AutofacContainer.Build(services)); }
static async Task Main(string[] args) { System.AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper; var builder = new HostBuilder() .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(Directory.GetCurrentDirectory()); config.AddEnvironmentVariables(); if (args != null) { config.AddCommandLine(args); } }) .ConfigureServices((hostContext, services) => { services.AddOptions(); #if DEBUG var AppSetting = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.debug.json") .Build(); #elif RELEASE var AppSetting = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); #endif //int scheduleSwitch = int.Parse(AppSetting["AppConfigs:ScheduleSwitch"]); //if (scheduleSwitch.Equals(1)) //{ //} services.Configure <AppSettings>(AppSetting); services.AddHttpClient(); services.AddSingleton <DBService>(); services.AddSingleton <Service_xuangubao>(); services.AddSingleton <MapperService>(); services.AddSingleton <IRedisService, RedisService>(); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); #if DEBUG services.AddHostedService <DevService>(); #endif services.AddSingleton <IHostedService, TimeJob>(); AutofacContainer.Build(services); }); await builder.RunConsoleAsync(); }
public static IServiceProvider BuildAutofacServiceProvider(this IServiceCollection services) { if (services == null) { throw new ArgumentNullException(nameof(services)); } return(AutofacContainer.Build(services)); }
public static IServiceProvider BuildAspectCoreWithAutofacServiceProvider(this IServiceCollection services, Action <IAspectConfiguration> configure = null) { if (services == null) { throw new ArgumentNullException(nameof(services)); } services.ConfigureDynamicProxy(configure); return(ServiceLocator.Current = AutofacContainer.Build(services, configure)); }
private void Window_Loaded(object sender, RoutedEventArgs e) { var settings = TryReadSettings(); var container = AutofacContainer.Build(this, settings); _rootLifetimeScope = container.BeginLifetimeScope(); var gamePresenter = _rootLifetimeScope.Resolve <IGamePresenter>(); gamePresenter.Start(); }
static void Main(string[] args) { var builder = new HostBuilder() .ConfigureAppConfiguration((hostContext, config) => { config.SetBasePath(Directory.GetCurrentDirectory()); config.AddJsonFile("Config.json", optional: true); }) .ConfigureServices((hostContext, services) => { services.AddSingleton <IHostLifetime, OwnLifetime>(); services.AddHostedService <HttpServerHosted>(); AutofacContainer.Register("Api.Services", "Api.IService"); AutofacContainer.SetCodeFirstAsync("Api.Models"); //使用codefirst AutofacContainer.Build(services); //使用ioc注入 }) .ConfigureLogging((hostingContext, logging) => { logging.AddEventLog(); //启用系统事件日志, logging.AddDebug(); logging.AddConsole(); logging.AddEventSourceLogger(); }); //builder.Build().Run(); HostFactory.Run(x => { //服务名称 x.SetServiceName("ApiService"); //服务展示名称 x.SetDisplayName("ApiService"); //服务描述 x.SetDescription("Api服务"); //服务启动类型:自动 x.StartAutomatically(); //x.RunAsLocalSystem(); x.Service <IHost>(s => { s.ConstructUsing(() => builder.Build()); s.WhenStarted(service => { service.Start(); }); s.WhenStopped(service => { service.StopAsync(); }); }); }); }
// 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_2); services.Configure <ForwardedHeadersOptions>(options => { options.KnownProxies.Add(IPAddress.Parse("10.0.0.100")); }); services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { //builder.WithOrigins(this.Configuration.GetSection("CorsIp")["IpAddress"]) builder.WithOrigins("*") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.AddSwaggerGen(gen => { gen.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }); /*AddAzureAd(options => * { * Configuration.Bind("AzureAd", options); * AzureAdOptions.Settings = options; * }) * .AddCookie();*/ services.Configure <AccountModel>(Configuration.GetSection("accountsetting")); services.AddHttpClient("chinacloudapi", x => { x.BaseAddress = new Uri("https://management.chinacloudapi.cn/subscriptions/"); x.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); }); services.AddHttpClient(); IocContainer autofac = new AutofacContainer(services); return(autofac.Build().FetchServiceProvider()); }
public static IServiceProvider BuildAspectCoreWithAutofacServiceProvider(this IServiceCollection services, Action <IAspectConfiguration> configure = null) { if (services == null) { throw new ArgumentNullException(nameof(services)); } if (configure == null) { configure = config => { config.Interceptors.AddTyped <FromDbContextFactoryInterceptor>(); }; } services.ConfigureDynamicProxy(configure); return(ServiceLocator.Current = AutofacContainer.Build(services, configure)); }
public static void Main(string[] args) { IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(AppContext.BaseDirectory) .AddJsonFile("appsettings.json", false, true) .Build(); IServiceCollection services = new ServiceCollection(); services.AddSingleton <IRedisCache, RedisCache>(); services.AddSingleton <RedisConfigurationOptions>(x => new RedisConfigurationOptions { EndPoint = configuration.GetSection("RedisConfigurationOptions:EndPoint")?.Value, Password = configuration.GetSection("RedisConfigurationOptions:Password")?.Value }); AutofacContainer.Build(services); var test = AutofacContainer.Resolve <RedisConfigurationOptions>(); Console.WriteLine("Hello World!"); }
public static IContainer ConfigureAutofac(this IServiceCollection services) { var container = new AutofacContainer(); return(container.Build(services)); }
// 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_2); services.Configure <ForwardedHeadersOptions>(options => { options.KnownProxies.Add(IPAddress.Parse("10.0.0.100")); }); services.AddCors(options => { options.AddPolicy(MyAllowSpecificOrigins, builder => { //builder.WithOrigins(this.Configuration.GetSection("CorsIp")["IpAddress"]) builder.WithOrigins("*") .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); services.AddSwaggerGen(gen => { gen.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" }); }); services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }); /*AddAzureAd(options => * { * Configuration.Bind("AzureAd", options); * AzureAdOptions.Settings = options; * }) * .AddCookie();*/ services.Configure <AccountModel>(Configuration.GetSection("accountsetting")); services.Configure <JwtSettings>(Configuration.GetSection("JwtSettings")); services.Configure <TokenResourceModel>(Configuration.GetSection("TokenResource")); //JwtSettings jwtSettings = new JwtSettings(); //Configuration.Bind("JwtSettings", jwtSettings); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidAudience = "http://localhost:44350", ValidIssuer = "http://localhost:44350", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JwtSettings:SecurityKey"])) }; }); services.AddHttpClient("chinacloudapi", x => { x.BaseAddress = new Uri("https://management.chinacloudapi.cn/subscriptions/"); x.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); }); services.AddHttpClient("LogAnalyResource", x => { x.BaseAddress = new Uri("https://api.loganalytics.azure.cn"); x.DefaultRequestHeaders.Add("Cache-Control", "no-cache"); }); services.AddHttpClient(); services.AddLogging(); services.AddScoped <JWTHelper>(); IocContainer autofac = new AutofacContainer(services); return(autofac.Build().FetchServiceProvider()); }