net core 3.1 webapi的開發遇到的問題


1.用的是工廠倉儲模式(數據層data)

public interface IRepositoryFactory
    {
        IRepository<T> CreateRepository<T>(IDBContext dataContext) where T : class;
    }
 public class RepositoryFactory : IRepositoryFactory
    {
        public IRepository<T> CreateRepository<T>(IDBContext dataContext) where T : class
        {
            return new Repository<T>(dataContext);
        }
    }
public class Repository<T> : IRepository<T> where T : class
    {
        private readonly DBContext DBContext;

        private readonly DbSet<T> dbset;
        public Repository(IDBContext _DBContext)
        {
            DBContext = _DBContext as DBContext;
            dbset = DBContext.Set<T>();
        }
  /// 泛型方法的實現

      /// <summary>
      /// 查詢
      /// </summary>
      /// <returns></returns>
      public IQueryable<T> Query()
      {
        return dbset;
      }

}
 public interface IRepository<T> : IDisposable where T : class
    {
        /// <summary>
        /// 事務
        /// </summary>
        /// <returns></returns>
        IDbContextTransaction BeginTransaction();

       ///泛型方法的定義

/// <summary>

       /// 查詢
       /// </summary>
       /// <returns></returns>
       IQueryable<T> Query();


}
public class DBContext : DbContext, IDBContext
    {
        public DBContext(DbContextOptions<DBContext> options
            ) : base(options)
        {

        }

        public override int SaveChanges()
        {
            return base.SaveChanges(true);
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Server=.;Data Source=(local);uid=sa;pwd=123456;DataBase=test");
            }
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.ApplyConfigurationsFromAssembly(typeof(CourseMap).Assembly);

            base.OnModelCreating(modelBuilder);
        }
    }

 在服務層

public interface IBaseService
    {
        IRepository<T> CreateService<T>() where T : class, new();
    }
public class BaseService : IBaseService
    {
        private readonly IRepositoryFactory _repfactory;

        private readonly IDBContext _context;

        public BaseService(IRepositoryFactory repfactory, IDBContext context)
        {
            _repfactory = repfactory;

            _context = context;
        }

        public IRepository<T> CreateService<T>() where T : class, new()
        {
            return _repfactory.CreateRepository<T>(_context);
        }
    }
 public interface IExampleService
    {
        /// <summary>
        /// 定義方法類型
        /// </summary>
        /// <returns></returns>
        Task<List<Example>> GetExampleListAsync();


    }
public class ExampleService : BaseService, IExampleService
    {
        private readonly IRepository<Example> _example;
        public CourseService(IRepositoryFactory repositoryFactory, IDBContext context) : base(repositoryFactory, context)
        {
            _example = this.CreateService<Example>();
          
        }
        public async Task<Example> GetExampleListAsync()
        {
              ///寫業務邏輯,控制器調用
        }      


    }    

然后在startup  的ConfigureServices注冊

services.AddScoped<IDBContext, DBContext>();
services.AddScoped<IRepositoryFactory, RepositoryFactory>();

2接口的調試,用swagger插件,需要有幾個地方注意(注意引用的包)

①控制器要加路由,不然不顯示,方式要加http,不然報錯,返回的json格式和后台定義的不一樣(大小寫不一樣)在注冊服務中加上下面代碼

 foreach (var item in GetClassName("xxx.Service"))
            {
                {
                    foreach (var typeArray in item.Value)
                    {
                        if (item.Key == typeof(Service.Interface.IBaseService))
                        {
                            continue;
                        }
                        services.AddScoped(typeArray, item.Key);
                    }
                }
                services.AddMvc().AddNewtonsoftJson(options =>
                {
                    options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    options.SerializerSettings.Formatting = Formatting.Indented;
                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
                }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            }



Dictionary<Type, Type[]> GetClassName(string assemblyName)
        {
            if (!String.IsNullOrEmpty(assemblyName))
            {
                Assembly assembly = Assembly.Load(assemblyName);
                List<Type> ts = assembly.GetTypes().ToList();

                var result = new Dictionary<Type, Type[]>();
                foreach (var item in ts.Where(s => !s.IsInterface))
                {
                    var interfaceType = item.GetInterfaces();
                    result.Add(item, interfaceType);
                }
                return result;
            }
            return new Dictionary<Type, Type[]>();
        }

在Configure中添加

       // 添加Swagger有關中間件
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/V1/swagger.json", "xxx.API");  
                //c.RoutePrefix = string.Empty;   設置swagger路由,默認是/swagger/index.html,注意端口號 
            });

 

②自宿運行兩種方式,一個是bin文件夾啟動,里面有端口號,也可以選擇api啟用用debug模式,release不能調試

遺留的問題1.Automap的使用,如何將Dto與實體映射,怎么配置文件,這樣只要配置一次,就可以使用

2 如何將list中的實體映射到dto中,不用foreach等循環

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM