AutoMapper记录
1.添加AutoMapper包
2.正常使用
1)生成MapperConfiguration
var config = new MapperConfiguration(cfg => cfg.CreateMap<TSource, TDestination>()); 2) 生成mapper
var mapper = config.CreateMapper();
3) 根据映射源对象实列获取需要的dto实列 return mapper.Map<TDestination>(source);
automapper的测试源码里就是上述这样,但这样不适合在项目中使用。
--Nancy和autofac的整合,在需要使用的地方直接注入就行。
1.安装包
Nancy
Autofac
autoMapper
Nancy.Bootstrappers.Autofac
2.autoMapperConfig
public static MapperConfiguration InitMapperConfig() { var config = new MapperConfiguration(cfg => cfg.AddProfile(new UserInfoProfile())); return config; }
3.autofac的module
public class AutoFacModule : Autofac.Module { protected override void Load(ContainerBuilder builder) { base.Load(builder); builder.RegisterInstance(MapperConfig.InitMapperConfig().CreateMapper()).As<IMapper>(); } }
4.AutofacNancyBootstrapper
public class CustomNancyModule : AutofacNancyBootstrapper { protected override void ApplicationStartup(ILifetimeScope container, IPipelines pipelines) { base.ApplicationStartup(container, pipelines); Conventions.ViewLocationConventions.Add( (viewName, model, context) => string.Concat("Views/", viewName)); CookieBasedSessions.Enable(pipelines); } protected override void ConfigureApplicationContainer(ILifetimeScope container) { base.ConfigureApplicationContainer(container); container.Update(builder => builder.RegisterModule<AutoFacModule>());//依赖注入 } protected override void RequestStartup(ILifetimeScope container, IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); } }
autofac的配置--程序集
var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList();=>
var assemblys = BuildManager.GetReferencedAssemblies().Cast<Assembly>().ToList();
private ContainerBuilder RegisterService () { var builder = new ContainerBuilder(); var baseType = typeof(IDependency); var assemblys = AppDomain.CurrentDomain.GetAssemblies().ToList(); var AllServices = assemblys .SelectMany(s => s.GetTypes()) .Where(p => baseType.IsAssignableFrom(p) && p != baseType); builder.RegisterControllers(assemblys.ToArray()); builder.RegisterAssemblyTypes(assemblys.ToArray()) .Where(t => baseType.IsAssignableFrom(t) && t != baseType) .AsImplementedInterfaces().InstancePerLifetimeScope(); return builder; }
--------------这种通过profile文件注入。
public static MapperConfiguration CreateMapperConfiguration()
{
var mappingAssemblies = AppDomain.CurrentDomain.GetAssemblies()
.ToList()
.Where(x => x.FullName.StartsWith("A", StringComparison.InvariantCultureIgnoreCase));
var allProfileTypes = new List<Type>();
foreach (var assembly in mappingAssemblies)
{
allProfileTypes.AddRange(assembly.TypesImplementing<Profile>());
}
var mapConfig = new MapperConfiguration(cfg =>
{
foreach (var profileType in allProfileTypes)
cfg.AddProfile((Profile)profileType.CreateInstance());
});
return mapConfig;
}
--Fasterflect.dll 程序集的扩展