• 跨域,批量注册服务


    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;
    }
    }

  • 相关阅读:
    BAT脚本批量调用Sql执行文件 (SqlServer 数据库)
    树莓派系统刻录到首次登陆等问题
    数据库视图的使用
    MQ配置安装
    PLSQL集合类型
    PLSQL-包函数存储过程
    Oracle 字段拆分替换在合并成一条
    ORACLE-EXP和IMP方法介绍
    javascript几个月前的时间
    返回顶部实现方式
  • 原文地址:https://www.cnblogs.com/csj007523/p/13369720.html
Copyright © 2020-2023  润新知