首页 > 其他分享 >.net 6及以上版本 WebAPI 初始化项目介绍

.net 6及以上版本 WebAPI 初始化项目介绍

时间:2024-07-10 14:52:47浏览次数:9  
标签:WebAPI 初始化 serviceType builder app class Services net public

从 ZR.Admin 里面 摘出一部分 作为参考 

1.Program.cs 

    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.
            builder.Services.AddControllersWithViews();

            builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            //消除Error unprotecting the session cookie警告
            builder.Services.AddDataProtection()
                .PersistKeysToFileSystem(new DirectoryInfo(Directory.GetCurrentDirectory() + Path.DirectorySeparatorChar + "DataProtection"));

            builder.Services.AddSession();
            builder.Services.AddHttpContextAccessor();
            //绑定整个对象到Model上
            builder.Services.Configure<OptionsSetting>(builder.Configuration);

            builder.Services.AddAppService();
            //初始化db
            DbExtension.AddDb(builder.Configuration);

            //builder.Services.AddMvc(options =>
            //    {
            //        options.Filters.Add(typeof(GlobalActionMonitor));//全局注册
            //    })
            //    .AddJsonOptions(options =>
            //    {
            //        options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeConverter());
            //        options.JsonSerializerOptions.Converters.Add(new JsonConverterUtil.DateTimeNullConverter());
            //    });

            builder.Services.AddSwaggerConfig();
     

            var app = builder.Build();
            InternalApp.ServiceProvider = app.Services;
            app.UseSwagger();

            //if (builder.Configuration["InitDb"].ParseToBool() == true)
            //{
            //    app.Services.InitDb();
            //}

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Home/Error");
            }
            //开启访问静态文件/wwwroot目录文件,要放在UseRouting前面
            app.UseStaticFiles();

            //开启路由访问
            app.UseRouting();

            app.UseAuthorization();

            //开启缓存
            app.UseResponseCaching();

            //使用全局异常中间件
            app.UseMiddleware<GlobalExceptionMiddleware>();

            app.MapControllerRoute(
                name: "default",
                pattern: "{controller=Home}/{action=Index}/{id?}");
           
            app.Run();
        }
    }

 

这里单独说一下  builder.Services.AddAppService();

2. 添加 静态扩展类 AppServiceExtensions

  public static class AppServiceExtensions
  {
      /// <summary>
      /// 注册引用程序域中所有有AppService标记的类的服务
      /// </summary>
      /// <param name="services"></param>
      public static void AddAppService(this IServiceCollection services)
      {
          //var assemblies = AppDomain.CurrentDomain.GetAssemblies();

          string []cls = new string[] { "MjBlog.Repository", "MjBlog.Service" };
          foreach (var item in cls)
          {
              Assembly assembly = Assembly.Load(item);
              Register(services, assembly);
          }
      }

      private static void Register(IServiceCollection services, Assembly assembly)
      {
          foreach (var type in assembly.GetTypes())
          {
              var serviceAttribute = type.GetCustomAttribute<AppServiceAttribute>();

              if (serviceAttribute != null)
              {
                  var serviceType = serviceAttribute.ServiceType;
                  //情况1 适用于依赖抽象编程,注意这里只获取第一个
                  if (serviceType == null && serviceAttribute.InterfaceServiceType)
                  {
                      serviceType = type.GetInterfaces().FirstOrDefault();
                  }
                  //情况2 不常见特殊情况下才会指定ServiceType,写起来麻烦
                  if (serviceType == null)
                  {
                      serviceType = type;
                  }

                  switch (serviceAttribute.ServiceLifetime)
                  {
                      case LifeTime.Singleton:
                          services.AddSingleton(serviceType, type);
                          break;
                      case LifeTime.Scoped:
                          services.AddScoped(serviceType, type);
                          break;
                      case LifeTime.Transient:
                          services.AddTransient(serviceType, type);
                          break;
                      default:
                          services.AddTransient(serviceType, type);
                          break;
                  }
                  //Console.WriteLine($"注册:{serviceType}");
              }
              else
              {
                  //Console.WriteLine($"注册:{serviceType}");
              }
          }
      }
  }

 

3.Service 和 Repository 配置 对应的 生命周期

  public interface IBaseRepository<T> : ISimpleClient<T> where T : class, new()
  {
       // 提供 增删改查 事务等接口
  }
  public class BaseRepository<T> : SimpleClient<T> where T : class, new()
  {
       public BaseRepository(ISqlSugarClient context = null) : base(context)
       {
            // 初始化数据库配置,多租户配置 
           // 提供基础 增删改查, 事务等执行方法
       }
  }

    /// <summary>
    /// 参考地址:https://www.cnblogs.com/kelelipeng/p/10643556.html
    /// 标记服务
    /// 如何使用?
    /// 1、如果服务是本身 直接在类上使用[AppService]
    /// 2、如果服务是接口 在类上使用 [AppService(ServiceType = typeof(实现接口))]
    /// </summary>
  [AttributeUsage(AttributeTargets.Class, Inherited = false)]
   public class AppServiceAttribute : System.Attribute
   {
      public LifeTime ServiceLifetime { get; set; } = LifeTime.Scoped;
      public Type ServiceType { get; set; }
      public bool InterfaceServiceType { get; set; }
   }
   
   public enum LifeTime
    {
        /// <summary>
        /// 每次都不一样(不管是不是同一个web请求)
        /// </summary>
        Transient, 
        /// <summary>
        /// 同一个web请求周期内 ,为同一个对象; 不同web请求,不同对象
        /// </summary>
        Scoped,
        /// <summary>
        /// 单例
        /// </summary>
        Singleton
    }

  [AppService(ServiceLifetime = LifeTime.Transient)]
  public class SysOperLogRepository : BaseRepository<SysOperLog>
  {
      // 标注 此仓储 生命周期 是 LifeTime.Transient
  }
      public interface IBaseService<T> : IBaseRepository<T> where T : class, new()
    {
    }
    public class BaseService<T> : BaseRepository<T> where T : class, new()
    {
       
    }
   public interface ISysOperLogService
   {
        public void InsertOperlog(SysOperLog operLog);
        public PagedInfo<SysOperLog> SelectOperLogList(SysOperLogDto operLog, PagerInfo pager);
   }

 /// <summary>
 /// 操作日志
 /// </summary>
 [AppService(ServiceType = typeof(ISysOperLogService), ServiceLifetime = LifeTime.Transient)]
 public class SysOperLogService : BaseService<SysOperLog>, ISysOperLogService
 {
     public SysOperLogRepository sysOperLogRepository;

     public SysOperLogService(SysOperLogRepository sysOperLog)
     {
         sysOperLogRepository = sysOperLog;
     }

     /// <summary>
     /// 新增操作日志操作
     /// </summary>
     /// <param name="operLog">日志对象</param>
     public void InsertOperlog(SysOperLog operLog)
     {

     }

     /// <summary>
     /// 查询系统操作日志集合
     /// </summary>
     /// <param name="operLog">操作日志对象</param>
     /// <param name="pager"></param>
     /// <returns>操作日志集合</returns>
     public PagedInfo<SysOperLog> SelectOperLogList(SysOperLogDto operLog, PagerInfo pager)
     {
         operLog.BeginTime = DateTimeHelper.GetBeginTime(operLog.BeginTime, -1);
         operLog.EndTime = DateTimeHelper.GetBeginTime(operLog.EndTime, 1);

         bool isDemoMode = AppSettings.GetAppConfig("DemoMode", false);
         if (isDemoMode)
         {
             return new PagedInfo<SysOperLog>();
         }
         var list = sysOperLogRepository.GetSysOperLog(operLog, pager);

         return list;
     }

4.再Control中使用的时候, 直接注入使用 

public class BlogController : Controller
    {
        private readonly ISysOperLogService _sysOperLogService;
        public BlogController(ISysOperLogService sysOperLogService)
        {
            _sysOperLogService = sysOperLogService;
        }

        public IActionResult Index()
        {
            var sysOperLog =new Model.Models.SysOperLog();
            _sysOperLogService.InsertOperlog(sysOperLog);
            return View();
        }
    }

 

标签:WebAPI,初始化,serviceType,builder,app,class,Services,net,public
From: https://www.cnblogs.com/mjxxsc/p/18294032

相关文章

  • YOLOv8-Seg改进:backbone主干改进 | 微软新作StarNet:超强轻量级Backbone | CVPR 2024
     ......
  • YOLOv8原创改进:backbone主干改进 | 微软新作StarNet:超强轻量级Backbone | CVPR 2024
     ......
  • asp.net webform在Linux上部署--jexus
    JexusWebServer官网什么是JexusJexus是“JexusWebServer”的常用简称,也可简称为“JWS”。Jexus是一款运行于Linux环境的具有高安全性、高可靠性的高性能WEB服务器和负载均衡网关服务器。除了具备通用WEB服务器所必备的功能外,Jexus还能直接支持各类Asp.NetWEB应用,并以特有......
  • Backend - C# 的日志Lognet4
    目录一、安装log4net插件(一)作用(二)操作(三)注意二、配置(一)配置AssemblyInfo.cs (二)配置log4net.config1.创建log4net.config文件(和program.cs同层级)2.设置文件属性3.其中,文件内容:三、使用(一)封装一个类,方便管理(二)调用(三)等级Level四、其他:简单日志(一)定义日志......
  • 昇思25天学习打卡营第12天|ShuffleNet图像分类
    ShuffleNet网络介绍        ShuffleNetV1是旷视科技提出的一种计算高效的CNN模型,和MobileNet,SqueezeNet等一样主要应用在移动端,所以模型的设计目标就是利用有限的计算资源来达到最好的模型精度。ShuffleNetV1的设计核心是引入了两种操作:PointwiseGroupConvolution......
  • .Net Core WebApi项目 Development模式下报错 System.InvalidOperationException 解决
    .NetCoreWebApi项目Development模式下报错System.InvalidOperationException:“Cannotresolvescopedservice'Microsoft.Extensions.Options.IOptionsSnapshot`1[Infrastructure.OptionsSetting]'fromrootprovider.” 但是在Production模式下,运行正常因为未设置的......
  • 使用Terminal.Gui构建功能强大的.NET控制台应用
    前言前段时间分享了一个库帮你轻松的创建漂亮的.NET控制台应用程序-Spectre.Console的文章教程,然后就有小伙伴提问:.NET控制台应用需要应对强交互性的场景,有什么好的解决方案?,今天大姚给大家分享一款适用于.NET的跨平台终端UI工具包,帮助大家快速构建功能强大的.NET控制台应......
  • 16、 Django-多表操作-多个模块的关联-一对一的增删改查- models.onetoone()
    一对一不是数据库的一个连表操作、而是Django独有的一个连表操作、一对一相当于是特殊的一对多的关系、只是相当于加了unique=True models.pyfromdjango.dbimportmodels#身份证classIDCard(models.Model):idcard_num=models.CharField(max_length=18,unique=......
  • TextCNN: Convolutional Neural Networks for Sentence Classification
    本文是CNN应用在NLP领域的开山之作。TextCNN的成功并不是网络结构的成功,而是通过引入已经训练好的词向量在多个数据集上达到了超越benchmark的表现,证明了构造更好的embedding,是提升NLP各项任务的关键能力。作者做了一系列实验,这些实验使用卷积神经网络(CNN)在预训练的词向量之上......
  • Dotnet算法与数据结构:Hashset, List对比
    哈希集A是存储唯一元素的集合。它通过在内部使用哈希表来实现这一点,该哈希表为基本操作(如添加、删除和包含)提供恒定时间平均复杂度(O(1))。此外,不允许重复元素,使其成为唯一性至关重要的场景的理想选择。另一方面,表示按顺序存储元素的动态数组。它允许重复元素并提供对元素的索引......