.net Core 学习笔记(实体字段映射,IOC注入)
https://github.com/wj1034184751/ADO.NetCore.git
先简单的做一个学习架子,
EF层用的是 EFCore(2.1.0)+ Pomelo.EntityFrameworkCore.MySql(2.1.0)
实体映射主要是用了这三个类:
public interface IEntityTypeConfiguration { void Map(ModelBuilder builder); } public interface IEntityTypeConfiguration<T> : IEntityTypeConfiguration where T : class { void Map(EntityTypeBuilder<T> builder); } public abstract class WGEntityTypeConfig<T> : IEntityTypeConfiguration<T> where T : class { public abstract void Map(EntityTypeBuilder<T> builder); public void Map(ModelBuilder builder) { Map(builder.Entity<T>()); } } public static class ModelBuilderExtentcs { private static IEnumerable<Type> GetMappingTypes(this Assembly assembly,Type mappingInterface) { return assembly.GetTypes().Where(x => !x.GetTypeInfo().IsAbstract && x.GetInterfaces(). Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface)); } public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder,Assembly assembly) { var mappingTypes = assembly.GetTypes() .Where(type => type.BaseType != null && type.BaseType.IsGenericType && type.BaseType.GetGenericTypeDefinition() == typeof(WGEntityTypeConfig<>)); //var mappingTypes = assembly.GetMappingTypes(typeof(WGEntityTypeConfig<>)); foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityTypeConfiguration>()) { config.Map(modelBuilder); } } }
然后在这里
接下来是简单的注入:
项目分成这几层:
BLL,DAL,EF,UI
BLL,DAL 层要实现注入可以加一个接口,IServiceSupportExten
然后
Assembly asmBLL = Assembly.Load(new AssemblyName("BLL")); var serviceBLLTypes = asmBLL.GetTypes().Where(t => typeof(IServiceSupportExten).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract); foreach (var serviceType in serviceBLLTypes) { foreach (var interType in serviceType.GetInterfaces()) { services.AddSingleton(interType, serviceType); } } Assembly asmDAL = Assembly.Load(new AssemblyName("DAL")); var serviceDALTypes = asmDAL.GetTypes().Where(t => typeof(IServiceSupportExten).IsAssignableFrom(t) && !t.GetTypeInfo().IsAbstract); foreach (var serviceType in serviceDALTypes) { foreach (var interType in serviceType.GetInterfaces()) { services.AddSingleton(interType, serviceType); } }
.net Core 默认提供了一种注入方式,然后,自己也去网上找了代码写了别一种