Blog.Core/Blog.Core.Tests/DependencyInjection/DI_Test.cs

159 lines
6.3 KiB
C#
Raw Normal View History

2019-04-11 00:28:53 +08:00
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using Blog.Core.AuthHelper;
using Blog.Core.Common;
2020-06-08 13:40:23 +08:00
using Blog.Core.Common.AppConfig;
using Blog.Core.Common.DB;
2021-07-29 15:29:13 +08:00
using Blog.Core.Common.Seed;
2022-01-29 15:59:29 +08:00
using Blog.Core.Extensions;
2020-07-30 18:33:09 +08:00
using Blog.Core.IRepository.Base;
using Blog.Core.Repository.Base;
2022-06-06 12:10:17 +08:00
using Blog.Core.Repository.MongoRepository;
2022-01-29 15:59:29 +08:00
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.Extensions.DependencyInjection;
2022-01-29 15:59:29 +08:00
using Microsoft.Extensions.DependencyInjection.Extensions;
2020-06-08 13:40:23 +08:00
using Microsoft.IdentityModel.Tokens;
2019-04-11 00:28:53 +08:00
using System.Reflection;
using System.Security.Claims;
using System.Text;
2024-07-31 17:44:17 +08:00
using Blog.Core.Common.Core;
using Blog.Core.Extensions.ServiceExtensions;
using Microsoft.Extensions.Logging;
2019-04-08 15:54:01 +08:00
2019-04-11 00:28:53 +08:00
namespace Blog.Core.Tests
2019-04-08 15:54:01 +08:00
{
2019-04-11 00:28:53 +08:00
public class DI_Test
2019-04-08 15:54:01 +08:00
{
/// <summary>
/// 连接字符串
/// Blog.Core
/// </summary>
public static MutiDBOperate GetMainConnectionDb()
{
2020-10-13 18:16:38 +08:00
var mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs.Find(x => x.ConnId == MainDb.CurrentDbConnId);
if (BaseDBConfig.MutiConnectionString.allDbs.Count > 0)
{
if (mainConnetctDb == null)
{
2020-10-13 18:16:38 +08:00
mainConnetctDb = BaseDBConfig.MutiConnectionString.allDbs[0];
}
}
else
{
throw new Exception("请确保appsettigns.json中配置连接字符串,并设置Enabled为true;");
}
return mainConnetctDb;
}
public IContainer DICollections()
{
2021-07-28 13:59:43 +08:00
var basePath = AppContext.BaseDirectory;
IServiceCollection services = new ServiceCollection();
2024-07-31 17:44:17 +08:00
services.ConfigureApplication();
services.AddLogging();
2023-11-24 20:12:02 +08:00
services.AddAutoMapperSetup();
2024-07-31 17:44:17 +08:00
services.AddCacheSetup();
services.AddSingleton(new AppSettings(basePath));
2020-06-08 13:40:23 +08:00
services.AddScoped<DBSeed>();
services.AddScoped<MyContext>();
//读取配置文件
var symmetricKeyAsBase64 = AppSecretConfig.Audience_Secret_String;
var keyByteArray = Encoding.ASCII.GetBytes(symmetricKeyAsBase64);
var signingKey = new SymmetricSecurityKey(keyByteArray);
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
var permission = new List<PermissionItem>();
var permissionRequirement = new PermissionRequirement(
"/api/denied",
permission,
ClaimTypes.Role,
AppSettings.app(new string[] { "Audience", "Issuer" }),
AppSettings.app(new string[] { "Audience", "Audience" }),
signingCredentials, //签名凭据
expiration: TimeSpan.FromSeconds(60 * 60) //接口的过期时间
);
services.AddSingleton(permissionRequirement);
//【授权】
services.AddAuthorization(options =>
{
options.AddPolicy(Permissions.Name,
policy => policy.Requirements.Add(permissionRequirement));
});
services.AddScoped<SqlSugar.ISqlSugarClient>(o =>
{
2021-11-18 10:32:41 +08:00
return new SqlSugar.SqlSugarScope(new SqlSugar.ConnectionConfig()
{
ConnectionString = GetMainConnectionDb().Connection, //必填, 数据库连接字符串
DbType = (SqlSugar.DbType)GetMainConnectionDb().DbType, //必填, 数据库类型
IsAutoCloseConnection = true, //默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
});
});
//实例化 AutoFac 容器
var builder = new ContainerBuilder();
//builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
builder.RegisterInstance(new LoggerFactory())
2024-07-31 17:44:17 +08:00
.As<ILoggerFactory>();
builder.RegisterGeneric(typeof(Logger<>))
2024-07-31 17:44:17 +08:00
.As(typeof(ILogger<>))
.SingleInstance();
//指定已扫描程序集中的类型注册为提供所有其实现的接口。
builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency(); //注册仓储
builder.RegisterGeneric(typeof(MongoBaseRepository<>)).As(typeof(IMongoBaseRepository<>)).InstancePerDependency(); //注册仓储
2020-07-30 18:33:09 +08:00
2022-01-29 15:59:29 +08:00
// 属性注入
var controllerBaseType = typeof(ControllerBase);
2023-11-24 20:12:02 +08:00
//builder.RegisterAssemblyTypes(typeof(Program).Assembly)
// .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
// .PropertiesAutowired();
var servicesDllFile = Path.Combine(basePath, "Blog.Core.Services.dll");
var assemblysServices = Assembly.LoadFrom(servicesDllFile);
builder.RegisterAssemblyTypes(assemblysServices)
2024-07-31 17:44:17 +08:00
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.PropertiesAutowired()
.EnableInterfaceInterceptors();
var repositoryDllFile = Path.Combine(basePath, "Blog.Core.Repository.dll");
var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
2022-01-29 15:59:29 +08:00
builder.RegisterAssemblyTypes(assemblysRepository)
2024-07-31 17:44:17 +08:00
.PropertiesAutowired().AsImplementedInterfaces();
2022-01-29 15:59:29 +08:00
services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
services.AddAutoMapperSetup();
//将services填充到Autofac容器生成器中
builder.Populate(services);
//使用已进行的组件登记创建新容器
2024-07-31 17:44:17 +08:00
var applicationContainer = builder.Build();
return applicationContainer;
}
2024-07-31 17:44:17 +08:00
public IServiceProvider Build()
{
var container = DICollections();
var serviceProvider = new AutofacServiceProvider(container);
serviceProvider.ConfigureApplication();
App.IsBuild = true;
App.IsRun = true;
return serviceProvider;
}
2019-04-08 15:54:01 +08:00
}
}