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. 从别人那里拿过来的工程,在Idea上打开时报错

    如果是这个错误:也许原因有很多种,但是不妨试一下⑴将给你项目工程的人的.idea文件夹删除,这样在你导入工程时,会生成一个属于你本地的.idea.⑵最好是使用SVN重新把项目工程检出(把项目下载下来, ...

  2. Rust 入门 (五)

    定义并介绍结构体 结构体和我们前面学习的元组类似,结构体中的每一项都可以是不同的数据类型.和元组不同的地方在于,我们需要给结构体的每一项命名.结构体较元组的优势是:我们声明和访问数据项的时候不必使用索 ...

  3. Ansible Playbooks 介绍 和 使用 一

    目录 Ansible Playbooks Playbooks 组成部分: YAML 介绍 YAML 语法 Ansible 基础元素 变量 facts registre 通过命令传递变量 通过roles ...

  4. Hadoop原生搭建

    版本:(centos7.6) 在开始搭建平台前我已经预装了MySQL ps:MySQL创建用户并授权: grant all privileges on *.* to ' with grant opti ...

  5. GItBook命令使用(持续更新)

    GitBook基本命令 gitbook init //初始化目录文件 gitbook help //列出gitbook所有的命令 gitbook --help //输出gitbook-cli的帮助信息 ...

  6. ansible源码安装、普通用户实现批量控制

    一.ansible简介 ansible是一款自动化运维工具,基于Python开发,集合了众多运维工具(puppet.chef.func.fabric)的优点,实现了批量系统配置.批量程序部署.批量运行 ...

  7. 2019-2020-1 20199304《Linux内核原理与分析》第四周作业

    第三章 MenuOs的构造 一.前情回顾 计算机的三大法宝: -存储程序计算机 -函数调用堆栈 -中断 操作系统的两把宝剑: -中断上下文的切换(保存现场和恢复现场) -进程上下文的切换 二.3.1 ...

  8. nginx部署安装

    首先需要下载Nginx软件包 nginx软件官方下载地址:[nginx官方下载连接](http://www.nginx.org) 建议选择稳定的软件版本,如果练习使用当然是无所谓,随便什么版本都可以, ...

  9. 深入比特币原理(三)——交易的输入(input)与输出(output)

    本节内容非常重要,如果你不能很好的掌握本节内容,你无法真正理解比特币的运行原理,请务必要学习清楚. 比特币的交易模型为UTXO(unspend transaction output),即只记录未花费的 ...

  10. js之观察者模式和发布订阅模式区别

    观察者模式(Observer) 观察者模式指的是一个对象(Subject)维持一系列依赖于它的对象(Observer),当有关状态发生变更时 Subject 对象则通知一系列 Observer 对象进 ...