using Autofac;
using Autofac.Extensions.DependencyInjection;
using Hangfire;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Microsoft.IdentityModel.Tokens;
using StackExchange.Redis;
using Study.APPlication;
using Study.APPlication.Authen;
using Study.DoMain.IRepository;
using Study.EntityFrameworkCore;
using Study.EntityFrameworkCore.Repository;
using Study.EntityFrameworkCore.Seed;
using Study.Redis;
using StudyServer.HangfireTask;
using StudyServer.WebSockets;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Text;

namespace StudyServer
{
public class Startup
{
public static ConnectionMultiplexer Redis;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }
private static IContainer Container { get; set; }

// 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).AddJsonOptions(
opt =>
{
opt.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
});

#region Hangfire

var HangfireConfig = Configuration.GetSection("HangfireConfig");
HangfireConfig hangfireConfig = new HangfireConfig();
hangfireConfig.ConnStr = HangfireConfig["ConnStr"];
int db = ;
int.TryParse(HangfireConfig["DB"], out db);
hangfireConfig.DB = db;
hangfireConfig.Prefix = HangfireConfig["Prefix"]; Redis = ConnectionMultiplexer.Connect(hangfireConfig.ConnStr);
services.AddHangfire(config => config.UseRedisStorage(Redis, new Hangfire.Redis.RedisStorageOptions()
{
Db = hangfireConfig.DB,
Prefix = hangfireConfig.Prefix
}));

#endregion

#region 授权管理

var audienceConfig = Configuration.GetSection("Authentication");
var symmetricKeyAsBase64 = audienceConfig["SecurityKey"];
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray); var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = audienceConfig["Issuer"],
ValidateAudience = true,
ValidAudience = audienceConfig["Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
};
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
//这个集合模拟用户权限表,可从数据库中查询出来 //如果第三个参数,是ClaimTypes.Role,上面集合的每个元素的Name为角色名称,如果ClaimTypes.Name,即上面集合的每个元素的Name为用户名
var permissionRequirement = new PermissionRequirement("/api/denied", ClaimTypes.Role, audienceConfig["Issuer"], audienceConfig["Audience"], signingCredentials, new TimeSpan( * , , )); services.AddAuthorization(options =>
{
options.AddPolicy("Permission",
policy => policy.Requirements.Add(permissionRequirement)); }).AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
//不使用https
o.RequireHttpsMetadata = false;
o.TokenValidationParameters = tokenValidationParameters;
});
//注入授权Handler
services.AddSingleton<IAuthorizationHandler, PermissionHandler>();
services.AddSingleton(permissionRequirement);

#endregion

#region Swagger

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Version = "v1.1.0",
Title = "WebAPI",
Description = "框架集合",
TermsOfService = "None",
Contact = new Swashbuckle.AspNetCore.Swagger.Contact { }
});
// c.OperationFilter<SwaggerFileHeaderParameter>();
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "API.XML");
c.IncludeXmlComments(xmlPath);
//手动高亮
//添加header验证信息
//c.OperationFilter<SwaggerHeader>();
var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
c.AddSecurityRequirement(security);//添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一致,这里是Bearer。
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "JWT授权(数据将在请求头中进行传输) 参数结构: \"Authorization: Bearer {token}\"",
Name = "Authorization",//jwt默认的参数名称
In = "header",//jwt默认存放Authorization信息的位置(请求头中)
Type = "apiKey"
}); });

#endregion

#region MySql

var connection = this.Configuration.GetValue<string>("ConnectionStrings");
services.AddDbContext<StudyDbContext>(options => options.UseMySql(connection));
services.BuildServiceProvider().GetService<StudyDbContext>().Database.Migrate();

#endregion

#region 配置跨域

services.AddCors(
options => options.AddPolicy(
"Host",
builder => builder
.WithOrigins(
Configuration["CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.ToArray()
)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetPreflightMaxAge(TimeSpan.FromHours())//预检请求过期时间,用于减少OPTIONS请求
)
);

#endregion

StartTaskInit.InitTask(ref services);
#region Redis

var section = Configuration.GetSection("RedisConfig");
string _connectionString = section.GetSection("ConnIP").Value;//连接字符串
string _instanceName = section.GetSection("InstanceName").Value; //实例名称
int _defaultDB = int.Parse(section.GetSection("DB").Value ?? ""); //默认数据库
services.AddSingleton(new RedisHelper(_connectionString, _instanceName, _defaultDB));

#endregion

#region 泛型依赖注入

var builders = new ContainerBuilder();//实例化 AutoFac  容器
builders.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerDependency();
var assemblys = Assembly.Load("Study.APPlication");//Service是继承接口的实现方法类库名称
var baseType = typeof(IDependency);//IDependency 是一个接口(所有要实现依赖注入的借口都要继承该接口)
builders.RegisterAssemblyTypes(assemblys)
.Where(m => baseType.IsAssignableFrom(m) && m != baseType)
.AsImplementedInterfaces().InstancePerLifetimeScope();
builders.Populate(services);
Container = builders.Build();

#endregion

return new AutofacServiceProvider(Container);

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, StudyDbContext context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
#region Swagger

app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ApiHelp V1"); });

#endregion

#region Hangfire

app.UseHangfireServer();
app.UseHangfireDashboard("/hangfire", new DashboardOptions()
{
//Authorization = new[] { new CustomAuthorizeFilter() }
});

#endregion

app.UseCors("Host");
ServiceLocator.Instance = app.ApplicationServices;
//初始化数据
SeedHelper.SeenData(context);

//开启task任务

using (var scope = ServiceLocator.Instance.CreateScope())
{
var ITask = scope.ServiceProvider.GetService<ITaskManager>();
ITask.Regist();
ITask.Run();
}

app.UseHttpsRedirection();
app.UseMvc();
app.Map("/ws", WebSocketXX.Map);
}
}
}

Autofac 泛型依赖注入的更多相关文章

  1. Spring基础—— 泛型依赖注入

    一.为了更加快捷的开发,为了更少的配置,特别是针对 Web 环境的开发,从 Spring 4.0 之后,Spring 引入了 泛型依赖注入. 二.泛型依赖注入:子类之间的依赖关系由其父类泛型以及父类之 ...

  2. NopCommerce使用Autofac实现依赖注入

    NopCommerce的依赖注入是用的AutoFac组件,这个组件在nuget可以获取,而IOC反转控制常见的实现手段之一就是DI依赖注入,而依赖注入的方式通常有:接口注入.Setter注入和构造函数 ...

  3. Autofac之依赖注入

    这里主要学习一下Autofac的依赖注入方式 默认构造函数注入 class A { public B _b; public A() { } public A(B b) { this._b = b; } ...

  4. Spring(十六):泛型依赖注入

    简介: Spring4.X之后开始支持泛型依赖注入. 使用示例: 1.定义实体 package com.dx.spring.bean.componentscan; import java.io.Ser ...

  5. Web API(六):使用Autofac实现依赖注入

    在这一篇文章将会讲解如何在Web API2中使用Autofac实现依赖注入. 一.创建实体类库 1.创建单独实体类 创建DI.Entity类库,用来存放所有的实体类,新建用户实体类,其结构如下: us ...

  6. Spring的泛型依赖注入

    Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用,(这样子类和子类对应的泛型类自动建立关系)具体说明: 泛型注入:就是Bean1和Bean2注入了泛型,并且Bean1和Bean ...

  7. 转载--浅谈spring4泛型依赖注入

    转载自某SDN-4O4NotFound Spring 4.0版本中更新了很多新功能,其中比较重要的一个就是对带泛型的Bean进行依赖注入的支持.Spring4的这个改动使得代码可以利用泛型进行进一步的 ...

  8. Spring初学之泛型依赖注入

    主要讲泛型依赖注入,所以核心在java文件,配置文件中只需配置扫描包即可,如下: <?xml version="1.0" encoding="UTF-8" ...

  9. NET Core源代码通过Autofac实现依赖注入

    查看.NET Core源代码通过Autofac实现依赖注入到Controller属性   阅读目录 一.前言 二.使用Autofac 三.最后 回到目录 一.前言 在之前的文章[ASP.NET Cor ...

随机推荐

  1. 实战webpack系列03

    03.Webpack的强大功能 一.生成Source Maps(使调试更容易) 通过简单的配置,webpack就可以在打包时为我们生成的source maps,这为我们提供了一种对应编译文件和源文件的 ...

  2. PHP页面跳转三种实现方法

    一.header()函数 header()函数是PHP中进行页面跳转的一种十分简单的方法.header()函数的主要功能是将HTTP协议标头(header)输出到浏览器.header()函数的定义如下 ...

  3. MySQL-简介-安装(5.5版和5.7版)

    1.什么是MySQL (1)MySQL是一种关联数据库管理系统. (2)关联数据库将数据保存在不同的表中,而不是将所有数据放在一个大仓库中,可以增加速度,提高灵活性. (3)MySQL使用的是数据库常 ...

  4. 重写TabBar遇到的按钮不显示的问题

    这里的控件frame没有进行设置,无法显示 这里初始化的按钮 frame也为0, 因此 在 重写某个控件的时候 一定要调用layoutSubviews这个方法来对这个控件内部的子控件进行赋值

  5. java8 按两个属性分组,并返回扁平List; stream排序

    --------------- java8 按两个属性分组,并返回扁平List /** * 设置大区小区分组排序 * @param dtoList */ private List<Perform ...

  6. cesium添加多个geojson文件并分别控制显示和隐藏

    /*获取geojson数据*/ function get_geojson(name,h,n){ let x=document.getElementById(n); if(x.className === ...

  7. Nginx 404 Not Found 解决办法

    环境:宝塔Nginx面板 解决办法: 宝塔面板--站点设置-配置文件. 去掉:   error_page 404 /404.html; 前面的 # 号.

  8. mininet(二)简单的路由实验

    mininet(一)实验环境搭建 mininet(二)简单的路由实验 mininet(三)简单的NAT实验 在网上找了 好几个代码都是不能直接复现成功,这里把自己实现成功的代码给大家演示一下. 实验的 ...

  9. 使用chole创建一个连接池

    using Chloe; using Chloe.Infrastructure; using Chloe.SqlServer; using System; using System.Collectio ...

  10. java开发中常用的Liunx操作命令

    查看所有端口的占用情况 netstat -nultp 其中State值为LISTEN则表示已经被占用 查看某个端口的占用情况: netstat -anp |grep 端口号 在liunx中启动tomc ...