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

从 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();
        }
    }

 

posted @ 2024-07-10 14:46  兴想事成  阅读(45)  评论(0编辑  收藏  举报