@@ -272,21 +272,30 @@ protected Expression CreateInstantiationExpression(Expression source, CompileArg
272272 protected virtual Expression CreateInstantiationExpression ( Expression source , Expression destination , CompileArgument arg )
273273 {
274274 //new TDestination()
275+
276+ //if there is constructUsing, use constructUsing
275277 var constructUsing = arg . Settings . ConstructUsingFactory ? . Invoke ( arg ) ;
276278 Expression newObj ;
277279 if ( constructUsing != null )
278280 newObj = constructUsing . Apply ( source ) . TrimConversion ( true ) . To ( arg . DestinationType ) ;
279- else if ( arg . DestinationType . GetTypeInfo ( ) . IsAbstract && arg . Settings . Includes . Count > 0 )
281+
282+ //if there is default constructor, use default constructor
283+ else if ( arg . DestinationType . HasDefaultConstructor ( ) )
284+ newObj = Expression . New ( arg . DestinationType ) ;
285+
286+ //if mapToTarget or include derived types, allow mapping & throw exception on runtime
287+ //instantiation is not needed
288+ else if ( destination != null || arg . Settings . Includes . Count > 0 )
280289 newObj = Expression . Throw (
281290 Expression . New (
282291 // ReSharper disable once AssignNullToNotNullAttribute
283292 typeof ( InvalidOperationException ) . GetConstructor ( new [ ] { typeof ( string ) } ) ,
284- Expression . Constant ( "Cannot instantiate abstract type: " + arg . DestinationType . Name ) ) ,
293+ Expression . Constant ( "Cannot instantiate type: " + arg . DestinationType . Name ) ) ,
285294 arg . DestinationType ) ;
286- else if ( destination == null || arg . DestinationType . HasDefaultConstructor ( ) )
287- newObj = Expression . New ( arg . DestinationType ) ;
295+
296+ //otherwise throw
288297 else
289- newObj = destination ;
298+ throw new InvalidOperationException ( $ "No default constructor for type ' { arg . DestinationType . Name } ', please use 'ConstructUsing'" ) ;
290299
291300 //dest ?? new TDest();
292301 return destination == null
0 commit comments