WYB
2021-03-22 91b8cdad021ab052e4991f3d41834a6f0ddc36b8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Autofac.Extras.DynamicProxy;
using AutoMapper;
using JiepeiWMS.AuthHelper;
using JiepeiWMS.Common;
using JiepeiWMS.Common.AppConfig;
using JiepeiWMS.Common.DB;
using JiepeiWMS.Common.LogHelper;
using JiepeiWMS.IRepository.Base;
using JiepeiWMS.IServices;
using JiepeiWMS.Model.Seed;
using JiepeiWMS.Repository.Base;
using JiepeiWMS.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Claims;
using System.Text;
using Xunit;
 
namespace JiepeiWMS.Tests
{
    public class DI_Test
    {
 
        [Fact]
        public void DI_Connet_Test()
        {
            var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
 
            IServiceCollection services = new ServiceCollection();
            services.AddAutoMapper(typeof(Startup));
 
            services.AddScoped<SqlSugar.ISqlSugarClient>(o =>
            {
                return new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
                {
                    ConnectionString = GetMainConnectionDb().Connection,//必填, 数据库连接字符串
                    DbType = (SqlSugar.DbType)GetMainConnectionDb().DbType,//必填, 数据库类型
                    IsAutoCloseConnection = true,//默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                    IsShardSameThread = true,//共享线程
                    InitKeyType = SqlSugar.InitKeyType.SystemTable//默认SystemTable, 字段信息读取, 如:该属性是不是主键,标识列等等信息
                });
            });
 
            //services.AddSingleton(new Appsettings(Env));
 
 
            //实例化 AutoFac  容器   
            var builder = new ContainerBuilder();
            builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
 
            //指定已扫描程序集中的类型注册为提供所有其实现的接口。
            //var assemblysServices = Assembly.Load("JiepeiWMS.Services");
            //builder.RegisterAssemblyTypes(assemblysServices).AsImplementedInterfaces();
            //var assemblysRepository = Assembly.Load("JiepeiWMS.Repository");
            //builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();
 
            var servicesDllFile = Path.Combine(basePath, "JiepeiWMS.Services.dll");
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            builder.RegisterAssemblyTypes(assemblysServices)
                         .AsImplementedInterfaces()
                         .InstancePerLifetimeScope()
                         .EnableInterfaceInterceptors();
 
            var repositoryDllFile = Path.Combine(basePath, "JiepeiWMS.Repository.dll");
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();
 
            //将services填充到Autofac容器生成器中
            builder.Populate(services);
 
            //使用已进行的组件登记创建新容器
            var ApplicationContainer = builder.Build();
 
            var blogservice = ApplicationContainer.Resolve<IBlogArticleServices>();
 
            Assert.True(ApplicationContainer.ComponentRegistry.Registrations.Count() > 0);
        }
 
 
        /// <summary>
        /// 连接字符串 
        /// JiepeiWMS
        /// </summary>
        public static MutiDBOperate GetMainConnectionDb()
        {
            var mainConnetctDb = BaseDBConfig.MutiConnectionString.Item1.Find(x => x.ConnId == MainDb.CurrentDbConnId);
            if (BaseDBConfig.MutiConnectionString.Item1.Count > 0)
            {
                if (mainConnetctDb == null)
                {
                    mainConnetctDb = BaseDBConfig.MutiConnectionString.Item1[0];
                }
            }
            else
            {
                throw new Exception("请确保appsettigns.json中配置连接字符串,并设置Enabled为true;");
            }
 
            return mainConnetctDb;
        }
 
        public IContainer DICollections()
        {
            var basePath = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;
 
            IServiceCollection services = new ServiceCollection();
            services.AddAutoMapper(typeof(Startup));
 
            services.AddSingleton(new Appsettings(basePath));
            services.AddSingleton(new LogLock(basePath));
            services.AddSingleton<IRedisCacheManager, RedisCacheManager>();
            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 =>
            {
                return new SqlSugar.SqlSugarClient(new SqlSugar.ConnectionConfig()
                {
                    ConnectionString = GetMainConnectionDb().Connection,//必填, 数据库连接字符串
                    DbType = (SqlSugar.DbType)GetMainConnectionDb().DbType,//必填, 数据库类型
                    IsAutoCloseConnection = true,//默认false, 时候知道关闭数据库连接, 设置为true无需使用using或者Close操作
                    IsShardSameThread = true,//共享线程
                    InitKeyType = SqlSugar.InitKeyType.SystemTable//默认SystemTable, 字段信息读取, 如:该属性是不是主键,标识列等等信息
                });
            });
 
            //实例化 AutoFac  容器   
            var builder = new ContainerBuilder();
            //builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();
 
            //指定已扫描程序集中的类型注册为提供所有其实现的接口。
 
            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IBaseRepository<>)).InstancePerDependency();//注册仓储
 
 
            var servicesDllFile = Path.Combine(basePath, "JiepeiWMS.Services.dll");
            var assemblysServices = Assembly.LoadFrom(servicesDllFile);
            builder.RegisterAssemblyTypes(assemblysServices)
                         .AsImplementedInterfaces()
                         .InstancePerLifetimeScope()
                         .EnableInterfaceInterceptors();
 
            var repositoryDllFile = Path.Combine(basePath, "JiepeiWMS.Repository.dll");
            var assemblysRepository = Assembly.LoadFrom(repositoryDllFile);
            builder.RegisterAssemblyTypes(assemblysRepository).AsImplementedInterfaces();
 
            //将services填充到Autofac容器生成器中
            builder.Populate(services);
 
            //使用已进行的组件登记创建新容器
            var ApplicationContainer = builder.Build();
 
            return ApplicationContainer;
        }
    }
}