跨域,批量注册服务

Posted csj007523

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了跨域,批量注册服务相关的知识,希望对你有一定的参考价值。

1.starup.cs

services.AddCors(m => m.AddPolicy("any", a => a.AllowAnyOrigin().AllowAnyOrigin().AllowAnyHeader()));

services.BatchRegisterService(new Assembly[] { Assembly.GetExecutingAssembly(), Assembly.Load("xxx.Pay.Service") }, typeof(IDependency));

services.BatchRegisterService(new Assembly[] { Assembly.GetExecutingAssembly(), Assembly.Load("xxx.Pay.DAL") }, typeof(IBusinessDAL));

 

2.ServiceRegisterProvider.cs

namespace xxx.Pay.Service
{
public static class ServiceRegisterProvider
{
/// <summary>
/// 批量注册服务
/// </summary>
/// <param name="services">DI服务</param>
/// <param name="assemblys">需要批量注册的程序集集合</param>
/// <param name="baseType">基础类/接口</param>
/// <param name="serviceLifetime">服务生命周期</param>
/// <returns></returns>
public static IServiceCollection BatchRegisterService(this IServiceCollection services, Assembly[] assemblys, Type baseType, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
{
List<Type> typeList = new List<Type>(); //所有符合注册条件的类集合
foreach (var assembly in assemblys)
{
//筛选当前程序集下符合条件的类
var types = assembly.GetTypes().Where(t => !t.IsInterface && !t.IsSealed && !t.IsAbstract && baseType.IsAssignableFrom(t));
if (types != null && types.Count() > 0)
typeList.AddRange(types);
}
if (typeList.Count() == 0)
return services;

var typeDic = new Dictionary<Type, Type[]>(); //待注册集合
foreach (var type in typeList)
{
var interfaces = type.GetInterfaces(); //获取接口
typeDic.Add(type, interfaces);
}
if (typeDic.Keys.Count() > 0)
{
foreach (var instanceType in typeDic.Keys)
{
foreach (var interfaceType in typeDic[instanceType])
{
//根据指定的生命周期进行注册
switch (serviceLifetime)
{
case ServiceLifetime.Scoped:
services.AddScoped(interfaceType, instanceType);
break;
case ServiceLifetime.Singleton:
services.AddSingleton(interfaceType, instanceType);
break;
case ServiceLifetime.Transient:
services.AddTransient(interfaceType, instanceType);
break;
}
}
}
}
return services;
}

}
}

 

 

3.controller

//提高性能
foreach (var dal in dals)
{
switch (dal.GetType())
{
case var d when d == typeof(SysUserDAL): this.userDAL = dal as SysUserDAL; break;
case var d when d == typeof(MerchantDAL): this.merchantDAL = dal as MerchantDAL; break;
}
}

以上是关于跨域,批量注册服务的主要内容,如果未能解决你的问题,请参考以下文章

C#后台HttpWebRequest模拟跨域Ajax请求,注册Windows服务到服务器上

Domino WEB方式批量注册用户

WEB安全新玩法 [11] 防范批量注册

阶段一-01.万丈高楼,地基首要-第3章 用户登录注册模块开发-3-10 设置跨域配置实现前后端联调

Saltstack批量安装部署Zabbix代理(附zabbix自动注册详解)

JAVAEE——宜立方商城11:sso登录注册功能实现通过token获得用户信息Ajax跨域请求(jsonp)