LuckyPennySoftware/AutoMapper · error · AutoMapperMappingException

Cannot create an instance of type {type}

Error message

Cannot create an instance of type {type}

What it means

ResolutionContext.CreateInstance obtains destination/resolver/converter instances through the configured service constructor (ServiceCtor, defaulting to the mapper's). If that factory returns null for the requested type, AutoMapper cannot continue and throws AutoMapperMappingException naming the type. The default factory only succeeds for types activatable with a parameterless constructor.

Source

Thrown at src/AutoMapper/ResolutionContext.cs:75

    /// <summary>
    /// Instance cache for resolving keeping track of depth
    /// </summary>
    private Dictionary<TypePair, int> TypeDepth
    {
        get
        {
            CheckDefault();
            return _typeDepth ??= [];
        }
    }
    TDestination IMapperBase.Map<TDestination>(object source) => ((IMapperBase)this).Map(source, default(TDestination));
    TDestination IMapperBase.Map<TSource, TDestination>(TSource source) => _mapper.Map(source, default(TDestination), this);
    TDestination IMapperBase.Map<TSource, TDestination>(TSource source, TDestination destination) => _mapper.Map(source, destination, this);
    object IMapperBase.Map(object source, Type sourceType, Type destinationType) => _mapper.Map(source, (object)null, this, sourceType, destinationType);
    object IMapperBase.Map(object source, object destination, Type sourceType, Type destinationType) => _mapper.Map(source, destination, this, sourceType, destinationType);
    TDestination IInternalRuntimeMapper.Map<TSource, TDestination>(TSource source, TDestination destination, ResolutionContext context,
        Type sourceType, Type destinationType, MemberMap memberMap) => _mapper.Map(source, destination, context, sourceType, destinationType, memberMap);
    internal object CreateInstance(Type type) => ServiceCtor()(type) ?? throw new AutoMapperMappingException("Cannot create an instance of type " + type);
    private Func<Type, object> ServiceCtor() => _options?.ServiceCtor ?? _mapper.ServiceCtor;
    internal object GetDestination(object source, Type destinationType) => InstanceCache.GetValueOrDefault(new(source, destinationType));
    internal void CacheDestination(object source, Type destinationType, object destination) => InstanceCache[new(source, destinationType)] = destination;
    internal void IncrementTypeDepth(TypeMap typeMap) => TypeDepth[typeMap.Types]++;
    internal void DecrementTypeDepth(TypeMap typeMap) => TypeDepth[typeMap.Types]--;
    internal bool OverTypeDepth(TypeMap typeMap)
    {
        if (!TypeDepth.TryGetValue(typeMap.Types, out int depth))
        {
            TypeDepth[typeMap.Types] = 1;
            depth = 1;
        }
        return depth > typeMap.MaxDepth;
    }
    internal bool IsDefault => this == _mapper.DefaultContext;
    Func<Type, object> IInternalRuntimeMapper.ServiceCtor => ServiceCtor();
    internal static void CheckContext(ref ResolutionContext resolutionContext)
    {

View on GitHub (pinned to dfa6dd587c)

Solutions

  1. Register the type (destination, resolver, converter) with your DI container or set cfg.ServiceCtor = t => serviceProvider.GetRequiredService(t).
  2. Map to a concrete type, or use ConstructUsing((s, ctx) => new Dest(...)) / As<Concrete>() for interface destinations.
  3. Ensure the destination has a public parameterless constructor, or supply ctor arguments via ForCtorParam.
  4. If using ConstructUsingServiceLocator, confirm the locator returns a non-null instance for that type.

Example fix

// before
var config = new MapperConfiguration(c => c.CreateMap<ISource, DestInterface>()); // DestInterface is abstract
var dest = mapper.Map<DestInterface>(src); // throws: cannot create instance

// after
var config = new MapperConfiguration(c => c.CreateMap<ISource, DestInterface>().As<ConcreteDest>());
var dest = mapper.Map<DestInterface>(src);
Defensive patterns

Strategy: validation

Validate before calling

static bool IsActivatable(Type t) =>
    !t.IsAbstract && !t.IsInterface && t.GetConstructor(Type.EmptyTypes) != null;

if (!IsActivatable(typeof(TDest))
    && configuration.FindTypeMapFor<TSource, TDestination>()?.CustomCtorExpression == null
    && serviceCtor(typeof(TDest)) == null)
{
    throw new InvalidOperationException($"No way to create {typeof(TDest)}. Register it or use ConstructUsing.");
}

var dest = mapper.Map<TDest>(source);

Type guard

static bool CanConstructDestination<TDest>(IServiceProvider sp) =>
    !typeof(TDest).IsAbstract && !typeof(TDest).IsInterface
    && (typeof(TDest).GetConstructor(Type.EmptyTypes) != null
        || sp.GetService(typeof(TDest)) != null);

Try / catch

try { dest = mapper.Map<TDest>(source); }
catch (AutoMapperMappingException ex) when (ex.Message.StartsWith("Cannot create an instance of type"))
{
    // register the type with DI / add ConstructUsing / As<Concrete>, then retry
}

Prevention

When it happens

Trigger: AutoMapper tries to activate a type the ServiceCtor cannot build: an abstract class or interface used as destination, a class with no public parameterless ctor and no ConstructUsing, or a value resolver/type converter/value configuration not registered with DI when ConstructUsingServiceLocator is in effect.

Common situations: Using AddAutoMapper with DI but forgetting to register the destination/resolver; mapping to an interface without a concrete As mapping; a custom ServiceCtor that returns null for unregistered types; resolver/converter classes needing constructor injection.


AI-assisted analysis of LuckyPennySoftware/AutoMapper@dfa6dd587c (2026-08-13). Data as JSON: /api/errors/21031746ede370ad. Report an issue: GitHub.