Skip to content

Config instance

chaowlert edited this page Feb 4, 2020 · 4 revisions

Config instance

You may wish to have different settings in different scenarios. If you would not like to apply setting at a static level, Mapster also provides setting instance configurations.

varconfig=newTypeAdapterConfig();config.Default.Ignore("Id");

For instance configurations, you can use the same NewConfig and ForType methods that are used at the global level with the same behavior: NewConfig drops any existing configuration and ForType creates or enhances a configuration.

config.NewConfig<TSource,TDestination>().Map(dest =>dest.FullName,
src =>string.Format("{0} {1}",src.FirstName,src.LastName));config.ForType<TSource,TDestination>().Map(dest =>dest.FullName,
src =>string.Format("{0} {1}",src.FirstName,src.LastName));

You can apply a specific config instance by passing it to the Adapt method. (NOTE: please reuse your config instance to prevent recompilation)

varresult=src.Adapt<TDestination>(config);

Or to an Mapper instance.

varmapper=newMapper(config);varresult=mapper.Map<TDestination>(src);

Clone

If you would like to create configuration instance from existing configuration, you can use Clone method. For example, if you would like to clone from global setting.

varnewConfig=TypeAdapterConfig.GlobalSettings.Clone();

Or clone from existing configuration instance

varnewConfig=oldConfig.Clone();

Fork

Fork is similar to Clone, but Fork will allow you to keep configuration and mapping in the same location. See (https://github.com/MapsterMapper/Mapster/wiki/Config-location) for more info.

varforked=mainConfig.Fork(config =>config.ForType<Poco,Dto>().Map(dest =>dest.code, src =>src.Id));vardto=poco.Adapt<Dto>(forked);

Clone this wiki locally