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等循环