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. Linux中shell基础、重定向、管道符、环境变量

    1.什么是shell Shell是系统的用户界面,提供了用户与内核进行交互操作的一种接口(命令解释器).它接收用户输入的命令并把它送入内核去执行.起着协调用户与系统的一致性和在用户与系统之间进行交互的 ...

  2. 【IntelliJ IDEA】IDEA自动生成serialVersionUID的办法

    digest:实体对象实现了java.io.Serializable接口后,一般都会提供一个serialVersionUID一做版本区分.在IDEA里,可以通过一些设置,帮助我们快速生成serialV ...

  3. kubeadm配置高可用etcd集群

    操作系统为ubuntu18 kubernetes版本为v1.15.1 k8s默认在控制平面节点上的kubelet管理的静态pod中运行单个成员的etcd集群,但这不是高可用的方案. etcd高可用集群 ...

  4. 2019-2020-9 20199317 《Linux内核原理与分析》第九周作业

    第8章  进程的切换和系统的一般执行过程 1  进程调度的时机 1.1  硬终端与软中断 进程调度的时机都与中断相关,中断有很多种,都是程序执行过程中的强制性转移,转移到操作系统内核相应的处理程序.中 ...

  5. PHP按二维数组中的某个值重新排序数组 usort的使用方法

    $arr[0] = ['aa'=>123,'bb'=>'abc']; $arr[1] = ['aa'=>456,'bb'=>'dfe']; usort($arr,ss('aa' ...

  6. js实现冒泡排序(bubble sort)快速排序(quick sort)归并排序(merge sort)

    排序问题相信大家都比较熟悉了.用js简单写了一下几种常用的排序实现.其中使用了es6的一些语法,并且不仅限于数字--支持各种类型的数据的排序.那么直接上代码: function compare (a, ...

  7. 关于javascript中=的返回值

    今天看了一段代码,大概是这样的: function test(){ a=4; b=5; return b=a; } test();//返回? 返回值是多少呢?运行结果是4 这可以理解为将a的值赋给b以 ...

  8. 在 Linux 部署多节点 Kubernetes 集群与 KubeSphere 容器平台

    KubeSphere 是在 Kubernetes 之上构建的以应用为中心的企业级容器平台,所有供为用户提供简单易用的操作界面以及向导式操作方式.同时,KubeSphere Installer 提供了 ...

  9. angularJS使用ocLazyLoad实现js延迟加载

    最近开发一个系统遇到了一个问题,用angular路由一个html片段,该片段需要使用一个js插件来实现一个富文本编辑器.关键问题在于必须要在片段加载后通过js与dom元素进行绑定.一开始想当然以为直接 ...

  10. Python的Requests库基本方法函数

    一.Requests 库的七个常用函数: 1. requests.request(method,url,**kwargs) :method:请求方式,对应get/put/post等七种 :拟获取页面的 ...