我们是五月的花海 , 用青春|

兴想事成

园龄:12年10个月粉丝:25关注:97

.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 @   兴想事成  阅读(50)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 Good-bye My Loneliness ZARD
  2. 2 Say OK Vanessa Hudgens
  3. 3 All The Love In The World The Corrs
  4. 4 Adesso E Fortuna ~炎と永遠~ 加藤いづみ
Say OK - Vanessa Hudgens
00:00 / 00:00
An audio error has occurred, player will skip forward in 2 seconds.

作词 : BIRGISSON, ARNTHOR/KOTECHA, SAVAN

作曲 : Savan Kotecha/Arnthor Birgisson

Vanessa Hudgens - Say OK

Album: V

You are fine

You are fine

You are fine

You are fine

You are sweet

But I'm still a bit naive with my heart

When you're close I don't breathe

I can't find the words to speak

I feel sparks

But I don't wanna be into you

If you are not looking for true love, oh oh

No I don't wanna start seeing you

If I can't be your only one

So tell me when it's not alright

When it's not ok

Will you try to make me feel better?

Will you say alright? (say alright)

Will you say ok? (Say ok)

Will you stick with me through whatever?

Or run away

(Say that it's gonna be alright)

(That it's gonna be ok)

Say OK

When you call I don't know

If I should pick up the phone every time

I'm not like all my friends

Who keep calling up the boys, I'm so shy

But I don't wanna be into you

If you don't treat me the right way

See I can only start seeing you

If you can make my heart feel safe (feel safe)

When it's not alright

When it's not ok

Will you try to make me feel better?

Will you say alright? (say alright)

Will you say ok? (Say ok)

Will you stick with me through whatever?

Or run away

(Say that it's gonna be alright)

(That it's gonna be ok)

(Don't run away, don't run away)

Let me know if it's gonna be you

Boy, you've got some things to prove

Let me know that you'll keep me safe

I don't want you to run away so

Let me know that you'll call on time

Let me know that you won't be shy

Will you wipe my tears away

Will you hold me closer

When it's not alright

When it's not ok

Will you try to make me feel better

Will you say alright? (say alright)

Will you say ok? (Say ok)

Will you stick with me through whatever?

Or run away

(Say that it's gonna be alright)

(That it's gonna be ok)

Say OK

(Don't run away, don't run away)

(Say that it's gonna be alright)

(That it's gonna be ok)

(Don't run away)

Will you say OK

(Say that it's gonna be alright)

(That it's gonna be ok)

(Don't run away)

You are fine

You are fine