/// <summary>
        /// 启用AutoMapper
        /// </summary>
        public static IApplicationBuilder UseAutoMapper(this IApplicationBuilder app,
                                                        Action <IMapperConfigurationExpression> additionalInitAction = null)
        {
            MapperConfigurationExpression cfg = new MapperConfigurationExpression();

            if (additionalInitAction != null)
            {
                additionalInitAction(cfg);
            }

            //获取已注册到IoC的所有Profile
            IMapTuple[] tuples = app.ApplicationServices.GetServices <IMapTuple>().ToArray();
            foreach (IMapTuple mapTuple in tuples)
            {
                mapTuple.CreateMap();
                cfg.AddProfile(mapTuple as Profile);
            }

            Mapper.Initialize(cfg);

            IMapper mapper = app.ApplicationServices.GetService <IMapper>();

            MapperExtensions.SetMapper(mapper);

            return(app);
        }
Example #2
0
        /// <summary>
        /// 应用模块服务
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public override void UsePack(IServiceProvider provider)
        {
            ILogger logger = provider.GetLogger <AutoMapperPack>();
            MapperConfigurationExpression cfg = provider.GetService <MapperConfigurationExpression>();

            //获取已注册到IoC的所有Profile
            IMapTuple[] tuples = provider.GetServices <IMapTuple>().ToArray();
            foreach (IMapTuple mapTuple in tuples)
            {
                mapTuple.CreateMap();
                cfg.AddProfile(mapTuple as Profile);
                logger.LogInformation($"初始化对象映射配对:{mapTuple.GetType()}");
            }

            //各个模块DTO的 IAutoMapperConfiguration 映射实现类
            IAutoMapperConfiguration[] configs = provider.GetServices <IAutoMapperConfiguration>().ToArray();
            foreach (IAutoMapperConfiguration config in configs)
            {
                config.CreateMaps(cfg);
                logger.LogInformation($"初始化对象映射配对:{config.GetType()}");
            }

            MapperConfiguration configuration = new MapperConfiguration(cfg);
            IMapper             mapper        = new AutoMapperMapper(configuration);

            MapperExtensions.SetMapper(mapper);
            logger.LogInformation($"初始化对象映射对象到 MapperExtensions:{mapper.GetType()},共包含 {configuration.GetMappers().Count()} 个映射配对");

            IsEnabled = true;
        }
Example #3
0
        /// <summary>
        /// 注册AutoMapper对象映射操作
        /// </summary>
        /// <param name="service">服务集合</param>
        public static void AddAutoMapper(this IServiceCollection service)
        {
            var mapper = new AutoMapperMapper();

            service.TryAddSingleton <IMapper>(mapper);
            MapperExtensions.SetMapper(mapper);
        }
Example #4
0
        /// <summary>
        /// 应用模块服务
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public override void UsePack(IServiceProvider provider)
        {
            MapperConfigurationExpression cfg = provider.GetService <MapperConfigurationExpression>();

            //获取已注册到IoC的所有Profile
            IMapTuple[] tuples = provider.GetServices <IMapTuple>().ToArray();
            foreach (IMapTuple mapTuple in tuples)
            {
                mapTuple.CreateMap();
                cfg.AddProfile(mapTuple as Profile);
            }

            //各个模块DTO的 IAutoMapperConfiguration 映射实现类
            IAutoMapperConfiguration[] configs = provider.GetServices <IAutoMapperConfiguration>().ToArray();
            foreach (IAutoMapperConfiguration config in configs)
            {
                config.CreateMaps(cfg);
            }

            MapperConfiguration configuration = new MapperConfiguration(cfg);

            IMapper mapper = new AutoMapperMapper(configuration);

            MapperExtensions.SetMapper(mapper);

            IsEnabled = true;
        }
        /// <summary>
        /// 测试 - 初始化
        /// </summary>
        public CrudServiceTest()
        {
            _id     = Guid.NewGuid();
            _id2    = Guid.NewGuid();
            _entity = new EntitySample(_id)
            {
                Name = "A"
            };
            _entity2 = new EntitySample(_id2)
            {
                Name = "B"
            };
            _dto = new DtoSample {
                Id = _id.ToString(), Name = "A"
            };
            _dto2 = new DtoSample {
                Id = _id2.ToString(), Name = "B"
            };
            _unitOfWork = Substitute.For <IUnitOfWork>();
            _repository = Substitute.For <IRepositorySample>();
            _service    = new CrudServiceSample(_unitOfWork, _repository);
            var mapper = new AutoMapperMapper();

            MapperExtensions.SetMapper(mapper);
        }
        public static IServiceCollection RegisterAutoMapper(this IServiceCollection services)
        {
            var mapper = ServiceStartup.MapperInitialize();

            MapperExtensions.SetMapper(mapper);
            services.AddSingleton(mapper);
            return(services);
        }
Example #7
0
        /// <summary>
        /// 开始执行框架初始化
        /// </summary>
        /// <param name="iocBuilder">依赖注入构建器</param>
        public void Initialize(IIocBuilder iocBuilder)
        {
            iocBuilder.CheckNotNull("iocBuilder");

            OSharpConfig config = OSharpConfig.Instance;

            //依赖注入初始化
            IServiceProvider provider = iocBuilder.Build();

            //对象映射功能初始化
            IMappersBuilder mappersBuilder = provider.GetService <IMappersBuilder>();
            IMapper         mapper         = provider.GetService <IMapper>();

            if (!_mapperInitialized && mapper != null)
            {
                if (mappersBuilder != null)
                {
                    IEnumerable <IMapTuple> mapTuples = provider.GetServices <IMapTuple>();
                    mappersBuilder.Build(mapTuples);
                }
                MapperExtensions.SetMaper(mapper);
                _mapperInitialized = true;
            }

            //日志功能初始化
            IBasicLoggingInitializer loggingInitializer = provider.GetService <IBasicLoggingInitializer>();

            if (!_basicLoggingInitialized && loggingInitializer != null)
            {
                loggingInitializer.Initialize(config.LoggingConfig);
                _basicLoggingInitialized = true;
            }

            //数据库初始化
            IDatabaseInitializer databaseInitializer = provider.GetService <IDatabaseInitializer>();

            if (!_databaseInitialized && databaseInitializer != null)
            {
                databaseInitializer.Initialize(config.DataConfig);
                _databaseInitialized = true;
            }

            //实体信息初始化
            IEntityInfoHandler entityInfoHandler = provider.GetService <IEntityInfoHandler>();

            if (!_entityInfoInitialized && entityInfoHandler != null)
            {
                entityInfoHandler.Initialize();
                _entityInfoInitialized = true;
            }
            //功能信息初始化
            IFunctionHandler functionHandler = provider.GetService <IFunctionHandler>();

            if (functionHandler != null)
            {
                functionHandler.Initialize();
            }
        }
        public void TestControllerTestIndex()
        {
            var        mapper = MapperExtensions.CreateMapper();
            var        sut    = new TestController(mapper, new MemoryTestRepository());
            ViewResult res    = (ViewResult)sut.Index(1);

            res.Model.Should().BeOfType <List <TestModel> >();
            if (res.Model is List <TestModel> items)
            {
                items.ForEach(x => x.Completed.Should().BeFalse());
            }
        }
Example #9
0
        public MapTest()
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.AddProfile <TestMapperConfiguration>();
            });

            AutoMapperConfiguration.Init(config);
            var mapper = new AutoMapperMapper();

            MapperExtensions.SetMapper(mapper);
        }
Example #10
0
        private void SetMapper()
        {
            MapperConfigurationExpression cfg = new MapperConfigurationExpression();

            var config = new Kira.LaconicInvoicing.Warehouse.Dtos.AutoMapperConfiguration();

            config.CreateMaps(cfg);

            Mapper.Initialize(cfg);
            var mapper = new AutoMapperMapper();

            MapperExtensions.SetMapper(mapper);
        }
Example #11
0
        private void DoAttributeBasedMappings()
        {
            var typesWithAttr = MapperExtensions.GetFoTypesWithAttr();

            if (typesWithAttr != null || typesWithAttr.Count() > 0)
            {
                foreach (var item in typesWithAttr)
                {
                    if (item != null && item.CustomAttributes != null && item.CustomAttributes.Count() > 0)
                    {
                        var customAttr = item.CustomAttributes.FirstOrDefault(x => x.AttributeType == typeof(FoSource));
                        if (customAttr != null)
                        {
                            var sourceType = (Type)customAttr.ConstructorArguments.FirstOrDefault(x => x.ArgumentType == typeof(Type)).Value;
                            var reverseMap = (bool)customAttr.ConstructorArguments.FirstOrDefault(x => x.ArgumentType == typeof(Boolean)).Value;

                            if (sourceType != null)
                            {
                                if (reverseMap == true)
                                {
                                    CreateMap(sourceType, item).ReverseMap();
                                }
                                else
                                {
                                    CreateMap(sourceType, item);
                                }
                            }

                            var sourceTypes = (ReadOnlyCollection <CustomAttributeTypedArgument>)customAttr.ConstructorArguments.FirstOrDefault(x => x.ArgumentType == typeof(Type[])).Value;
                            if (sourceTypes != null)
                            {
                                foreach (var typeItem in sourceTypes)
                                {
                                    if (reverseMap == true)
                                    {
                                        CreateMap(typeItem.Value as Type, item).ReverseMap();
                                    }
                                    else
                                    {
                                        CreateMap(typeItem.Value as Type, item);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #12
0
        /// <summary>
        /// 测试 - 初始化
        /// </summary>
        public QueryServiceTest()
        {
            _id     = Guid.NewGuid();
            _id2    = Guid.NewGuid();
            _entity = new EntitySample(_id)
            {
                Name = "A"
            };
            _entity2 = new EntitySample(_id2)
            {
                Name = "B"
            };
            _repository = Substitute.For <IRepositorySample>();
            _service    = new QueryServiceSample(_repository);
            var mapper = new AutoMapperMapper();

            MapperExtensions.SetMapper(mapper);
        }
Example #13
0
        private void SourceToTargetMapping(FoMapping map)
        {
            try
            {
                if (map == null)
                {
                    throw new Exception("Invalid FoConfiguration in appsettings.json ! (FoMapper error)");
                }

                if (map.SourceMember.NameSpace == null || map.TargetMember.NameSpace == null)
                {
                    throw new Exception("You should specify a valid NameSpace for each item in appsettings.json! (FoMapper error)");
                }

                var sourceNameSpace = map.SourceMember.NameSpace;
                var sourceBaseType  = map.SourceMember.BaseTypeFullName.ToBaseType();
                var sourceTypes     = MapperExtensions.GetFoTypes(sourceNameSpace, sourceBaseType);

                var targetNameSpace = map.TargetMember.NameSpace;
                var targetBaseType  = map.TargetMember.BaseTypeFullName.ToBaseType();
                var targetTypes     = MapperExtensions.GetFoTypes(targetNameSpace, targetBaseType);

                foreach (var item in targetTypes)
                {
                    Type entityType = null;
                    entityType = sourceTypes.FirstOrDefault(x => x.Name.ClearMapType(map.SourceMember) == item.Name.ClearMapType(map.TargetMember));
                    if (entityType != null)
                    {
                        if (map.ReverseMap)
                        {
                            CreateMap(entityType, item).ReverseMap();
                        }
                        else
                        {
                            CreateMap(entityType, item);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public async Task <AuthResultModel> AuthenticateUser(AuthModelWithRefreshToken data)
        {
            AuthResultModel result = null;

            try
            {
                var authData = await _authServiceRepository.GetUserByRefreshToken(data.RefreshToken);

                result = MapperExtensions.Convert <AuthData, AuthResultModel>(authData);
                logger.Information($"AuthenticateUser [RefreshToken ]  by {data.RefreshToken} was successfully");
            }
            catch (Exception e)
            {
                logger.Error($"Method: AuthenticateUser with RefreshToken  Message: {e.Message}");
                throw;
            }

            return(result);
        }
Example #15
0
        /// <summary>
        /// 使用模块服务
        /// </summary>
        /// <param name="provider"></param>
        public override void UseModule(IServiceProvider provider)
        {
            MapperConfigurationExpression cfg = provider.GetService <MapperConfigurationExpression>() ?? new MapperConfigurationExpression();

            //获取已注册到IoC的所有Profile
            IMapTuple[] tuples = provider.GetServices <IMapTuple>().ToArray();
            foreach (IMapTuple mapTuple in tuples)
            {
                mapTuple.CreateMap();
                cfg.AddProfile(mapTuple as Profile);
            }

            Mapper.Initialize(cfg);

            IMapper mapper = provider.GetService <IMapper>();

            MapperExtensions.SetMapper(mapper);

            IsEnabled = true;
        }
        public async Task <AuthResultModel> AuthenticateUser(AuthModelWithCredentials data)
        {
            AuthResultModel result = null;

            try
            {
                var authData = await _authServiceRepository.GetUserByСredentials(data.Login, data.Password);

                result = MapperExtensions.Convert <AuthData, AuthResultModel>(authData);

                logger.Information($"AuthenticateUser [WithCredentials]  by {data.Login} was successfully");
            }
            catch (Exception e)
            {
                logger.Error($"Method: AuthenticateUser With Credentials Message: {e.Message}");
                throw;
            }

            return(result);
        }
Example #17
0
        /// <summary>
        /// 注册AutoMapper对象映射操作
        /// </summary>
        /// <param name="services">服务集合</param>
        public static void AddAutoMapper(this IServiceCollection services)
        {
            var typeFinder           = services.GetOrAddTypeFinder <ITypeFinder>(assemblyFinder => new TypeFinder(assemblyFinder));
            var mapperConfigurations = typeFinder.Find <IOrderedMapperProfile>();
            var instances            = mapperConfigurations.Select(mapperConfiguration =>
                                                                   (IOrderedMapperProfile)Activator.CreateInstance(mapperConfiguration))
                                       .OrderBy(mapperConfiguration => mapperConfiguration.Order);
            var config = new MapperConfiguration(cfg =>
            {
                foreach (var instance in instances)
                {
                    Debug.WriteLine($"初始化AutoMapper配置:{instance.GetType().FullName}");
                    cfg.AddProfile(instance.GetType());
                }
            });

            AutoMapperConfiguration.Init(config);
            var mapper = new AutoMapperMapper();

            services.TryAddSingleton <IMapper>(mapper);
            MapperExtensions.SetMapper(mapper);
        }
        /// <summary>
        /// 将数据源映射为指定<typeparamref name="TOutputDto"/>的集合,
        /// 并验证数据的<see cref="DataAuthOperation.Update"/>,<see cref="DataAuthOperation.Delete"/>数据权限状态
        /// </summary>
        public static IQueryable <TOutputDto> ToOutput <TEntity, TOutputDto>(this IQueryable <TEntity> source, bool getKey = false)
        {
            if (!typeof(TOutputDto).IsBaseOn <IDataAuthEnabled>() || getKey)
            {
                return(MapperExtensions.ToOutput <TEntity, TOutputDto>(source));
            }

            List <TEntity>       entities   = source.ToList();
            List <TOutputDto>    dtos       = new List <TOutputDto>();
            Func <TEntity, bool> updateFunc = FilterHelper.GetDataFilterExpression <TEntity>(null, DataAuthOperation.Update).Compile();
            Func <TEntity, bool> deleteFunc = FilterHelper.GetDataFilterExpression <TEntity>(null, DataAuthOperation.Delete).Compile();

            foreach (TEntity entity in entities)
            {
                TOutputDto       dto  = entity.MapTo <TOutputDto>();
                IDataAuthEnabled dto2 = (IDataAuthEnabled)dto;
                dto2.Updatable = updateFunc(entity);
                dto2.Deletable = deleteFunc(entity);
                dtos.Add(dto);
            }
            return(dtos.AsQueryable());
        }
        public async Task <AuthResultModel> UpdateRefreshToken(UpdateRefreshTokenModel model)
        {
            AuthResultModel result = null;

            try
            {
                await _authServiceRepository.UpdateRefreshToken(model.Id, model.RefreshToken,
                                                                model.RefreshTokenExpiryTime);

                var authData = await _authServiceRepository.GetUserByRefreshToken(model.RefreshToken);

                result = MapperExtensions.Convert <AuthData, AuthResultModel>(authData);

                logger.Information($"UpdateRefreshToken for user id: {model.Id} was successfully");
            }
            catch (Exception e)
            {
                logger.Error($"Method: UpdateRefreshToken Message: {e.Message}");
                throw;
            }

            return(result);
        }
Example #20
0
 /// <summary>
 /// 初始化一个<see cref="MicrosoftAuthorizationProviderTest"/>类型的实例
 /// </summary>
 public MicrosoftAuthorizationProviderTest(ITestOutputHelper output)
 {
     _output   = output;
     _provider = new MicrosoftAuthorizationProvider(new TestMicrosoftAuthorizationConfigProvider());
     MapperExtensions.SetMapper(new AutoMapperMapper());
 }
Example #21
0
        protected override void Configure()
        {
            MapperExtensions.CreateActionResultMap <Reservation, Dto.ReservationResult>();

            Mapper.CreateMap <Reservation, Dto.ReservationRequest>();
        }
Example #22
0
        /// <summary>
        /// 开始执行框架初始化
        /// </summary>
        /// <param name="iocBuilder">依赖注入构建器</param>
        public void Initialize(IIocBuilder iocBuilder)
        {
            iocBuilder.CheckNotNull("iocBuilder");

            OSharpConfig config = OSharpConfig.Instance;

            //依赖注入初始化
            IServiceProvider provider = iocBuilder.Build();

            //对象映射功能初始化
            IMappersBuilder mappersBuilder = provider.GetService <IMappersBuilder>();
            IMapper         mapper         = provider.GetService <IMapper>();

            if (!_mapperInitialized)
            {
                if (mappersBuilder != null)
                {
                    IEnumerable <IMapTuple> mapTuples = provider.GetServices <IMapTuple>();
                    mappersBuilder.Build(mapTuples);
                }
                if (mapper != null)
                {
                    MapperExtensions.SetMaper(mapper);
                }
                _mapperInitialized = true;
            }

            //日志功能初始化
            IBasicLoggingInitializer loggingInitializer = provider.GetService <IBasicLoggingInitializer>();

            if (!_basicLoggingInitialized && loggingInitializer != null)
            {
                loggingInitializer.Initialize(config.LoggingConfig);
                _basicLoggingInitialized = true;
            }

            //数据库初始化
            IDatabaseInitializer databaseInitializer = provider.GetService <IDatabaseInitializer>();

            if (!_databaseInitialized)
            {
                if (databaseInitializer == null)
                {
                    throw new InvalidOperationException(Resources.FrameworkInitializer_DatabaseInitializeIsNull);
                }
                databaseInitializer.Initialize(config.DataConfig);
                _databaseInitialized = true;
            }

            //实体信息初始化
            if (!_entityInfoInitialized)
            {
                IEntityInfoHandler entityInfoHandler = provider.GetService <IEntityInfoHandler>();
                if (entityInfoHandler == null)
                {
                    throw new InvalidOperationException(Resources.FrameworkInitializer_EntityInfoHandlerIsNull);
                }
                entityInfoHandler.Initialize();
                _entityInfoInitialized = true;
            }
            //功能信息初始化
            IFunctionHandler functionHandler = provider.GetService <IFunctionHandler>();

            if (functionHandler == null)
            {
                throw new InvalidOperationException(Resources.FrameworkInitializer_FunctionHandlerIsNull);
            }
            functionHandler.Initialize();
        }
Example #23
0
 private void OneTimeConfigurations()
 {
     MapperExtensions.Configure();
 }
Example #24
0
        public MapTest()
        {
            var mapper = new AutoMapperMapper();

            MapperExtensions.SetMapper(mapper);
        }
Example #25
0
 public void OneTimeSetUp()
 {
     _mapper = MapperExtensions.CreateMapper(new ContactProfile());
 }
 /// <summary>
 /// 初始化一个<see cref="GithubAuthorizationProviderTest"/>类型的实例
 /// </summary>
 public GithubAuthorizationProviderTest(ITestOutputHelper output)
 {
     _output   = output;
     _provider = new GithubAuthorizationProvider(new TestGithubAuthorizationConfigProvider());
     MapperExtensions.SetMapper(new AutoMapperMapper());
 }
Example #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="provider"></param>
        public static void UsePack(IServiceProvider provider)
        {
            IMapper mapper = provider.GetService <IMapper>();

            MapperExtensions.SetMapper(mapper);
        }