Autofac 泛型依赖注入
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 泛型依赖注入的更多相关文章
- Spring基础—— 泛型依赖注入
一.为了更加快捷的开发,为了更少的配置,特别是针对 Web 环境的开发,从 Spring 4.0 之后,Spring 引入了 泛型依赖注入. 二.泛型依赖注入:子类之间的依赖关系由其父类泛型以及父类之 ...
- NopCommerce使用Autofac实现依赖注入
NopCommerce的依赖注入是用的AutoFac组件,这个组件在nuget可以获取,而IOC反转控制常见的实现手段之一就是DI依赖注入,而依赖注入的方式通常有:接口注入.Setter注入和构造函数 ...
- Autofac之依赖注入
这里主要学习一下Autofac的依赖注入方式 默认构造函数注入 class A { public B _b; public A() { } public A(B b) { this._b = b; } ...
- Spring(十六):泛型依赖注入
简介: Spring4.X之后开始支持泛型依赖注入. 使用示例: 1.定义实体 package com.dx.spring.bean.componentscan; import java.io.Ser ...
- Web API(六):使用Autofac实现依赖注入
在这一篇文章将会讲解如何在Web API2中使用Autofac实现依赖注入. 一.创建实体类库 1.创建单独实体类 创建DI.Entity类库,用来存放所有的实体类,新建用户实体类,其结构如下: us ...
- Spring的泛型依赖注入
Spring 4.x 中可以为子类注入子类对应的泛型类型的成员变量的引用,(这样子类和子类对应的泛型类自动建立关系)具体说明: 泛型注入:就是Bean1和Bean2注入了泛型,并且Bean1和Bean ...
- 转载--浅谈spring4泛型依赖注入
转载自某SDN-4O4NotFound Spring 4.0版本中更新了很多新功能,其中比较重要的一个就是对带泛型的Bean进行依赖注入的支持.Spring4的这个改动使得代码可以利用泛型进行进一步的 ...
- Spring初学之泛型依赖注入
主要讲泛型依赖注入,所以核心在java文件,配置文件中只需配置扫描包即可,如下: <?xml version="1.0" encoding="UTF-8" ...
- NET Core源代码通过Autofac实现依赖注入
查看.NET Core源代码通过Autofac实现依赖注入到Controller属性 阅读目录 一.前言 二.使用Autofac 三.最后 回到目录 一.前言 在之前的文章[ASP.NET Cor ...
随机推荐
- Python开发-实现Excel套打打印
一.目的 目前本人就职与甲方的工作,由于公司的ERP比较烂无法完美的设计套打,就想着自己用Python开发一个套打工具. 二.开发过程 刚开始我打算用Html的方式生成打印的文档,但是有两个无法解决的 ...
- .net反编译原理
目录 目录 前言 ILdasm ILasm 结语 推荐文献 目录 NLog日志框架使用探究-1 NLog日志框架使用探究-2 科学使用Log4View2 前言 本来没有想写反编译相关的文章,但是写着写 ...
- Java 虚拟机结构
一 数据类型 与 Java 程序语言中的数据类型相似,Java 虚拟机可以操作的数据类型可分为两类:原始类型(Primitive Types,也经常翻译为原生类型或者基本类型)和引用类型(Refere ...
- 算法上机题目mergesort,priority queue,Quicksort,divide and conquer
1.Implement exercise 2.3-7. 2. Implement priority queue. 3. Implement Quicksort and answer the follo ...
- 2019-2020-7 20199317《Linux内核原理与分析》第七周作业
第6章 进程的描述和进程的创建 1 进程的描述 操作系统内核实现操作系统的三大管理功能,即进程管理.内存管理和文件系统.其中,操作系统内核中最核心的功能是进程管理.为了管理进程,内核要 ...
- Spring Cloud Hoxton正式发布,Spring Boot 2.2 不再孤单
距离Spring Boot 2.2.0的发布已经有一个半月左右时间,由于与之匹配的Spring Cloud版本一直没有Release,所以在这期间碰到不少读者咨询的问题都是由于Spring Boot和 ...
- 基于netty4.x开发时间服务器
在写代码之前 先了解下Reactor模型: Reactor单线程模型就是指所有的IO操作都在同一个NIO线程上面完成的,也就是IO处理线程是单线程的.NIO线程的职责是: (1)作为NIO服务端,接收 ...
- layui中formSelects的使用
1.下载 下载地址:https://github.com/hnzzmsf/layui-formSelects 2. 引入 //引入formSelects.css <link rel=" ...
- 如何在ASP.NET Core 中快速构建PDF文档
比如我们需要ASP.NET Core 中需要通过PDF来进行某些简单的报表开发,随着这并不难,但还是会手忙脚乱的去搜索一些资料,那么恭喜您,这篇帖子会帮助到您,我们就不会再去浪费一些宝贵的时间. 在本 ...
- python光标图片获取
# -*- coding:utf-8 -*- import win32api import win32gui,win32ui import time while True : time.sleep(1 ...