{"record":{"id":"21031746ede370ad","repo":"LuckyPennySoftware/AutoMapper","slug":"cannot-create-an-instance-of-type-type","errorCode":null,"errorMessage":"Cannot create an instance of type {type}","messagePattern":"Cannot create an instance of type (.+?)","errorType":"exception","errorClass":"AutoMapperMappingException","httpStatus":null,"severity":"error","filePath":"src/AutoMapper/ResolutionContext.cs","lineNumber":75,"sourceCode":"    /// <summary>\n    /// Instance cache for resolving keeping track of depth\n    /// </summary>\n    private Dictionary<TypePair, int> TypeDepth\n    {\n        get\n        {\n            CheckDefault();\n            return _typeDepth ??= [];\n        }\n    }\n    TDestination IMapperBase.Map<TDestination>(object source) => ((IMapperBase)this).Map(source, default(TDestination));\n    TDestination IMapperBase.Map<TSource, TDestination>(TSource source) => _mapper.Map(source, default(TDestination), this);\n    TDestination IMapperBase.Map<TSource, TDestination>(TSource source, TDestination destination) => _mapper.Map(source, destination, this);\n    object IMapperBase.Map(object source, Type sourceType, Type destinationType) => _mapper.Map(source, (object)null, this, sourceType, destinationType);\n    object IMapperBase.Map(object source, object destination, Type sourceType, Type destinationType) => _mapper.Map(source, destination, this, sourceType, destinationType);\n    TDestination IInternalRuntimeMapper.Map<TSource, TDestination>(TSource source, TDestination destination, ResolutionContext context,\n        Type sourceType, Type destinationType, MemberMap memberMap) => _mapper.Map(source, destination, context, sourceType, destinationType, memberMap);\n    internal object CreateInstance(Type type) => ServiceCtor()(type) ?? throw new AutoMapperMappingException(\"Cannot create an instance of type \" + type);\n    private Func<Type, object> ServiceCtor() => _options?.ServiceCtor ?? _mapper.ServiceCtor;\n    internal object GetDestination(object source, Type destinationType) => InstanceCache.GetValueOrDefault(new(source, destinationType));\n    internal void CacheDestination(object source, Type destinationType, object destination) => InstanceCache[new(source, destinationType)] = destination;\n    internal void IncrementTypeDepth(TypeMap typeMap) => TypeDepth[typeMap.Types]++;\n    internal void DecrementTypeDepth(TypeMap typeMap) => TypeDepth[typeMap.Types]--;\n    internal bool OverTypeDepth(TypeMap typeMap)\n    {\n        if (!TypeDepth.TryGetValue(typeMap.Types, out int depth))\n        {\n            TypeDepth[typeMap.Types] = 1;\n            depth = 1;\n        }\n        return depth > typeMap.MaxDepth;\n    }\n    internal bool IsDefault => this == _mapper.DefaultContext;\n    Func<Type, object> IInternalRuntimeMapper.ServiceCtor => ServiceCtor();\n    internal static void CheckContext(ref ResolutionContext resolutionContext)\n    {","sourceCodeStart":57,"sourceCodeEnd":93,"githubUrl":"https://github.com/LuckyPennySoftware/AutoMapper/blob/dfa6dd587c5854b4beee5934beb39ba6e9569b84/src/AutoMapper/ResolutionContext.cs#L57-L93","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Register the type (destination, resolver, converter) with your DI container or set cfg.ServiceCtor = t => serviceProvider.GetRequiredService(t).","Map to a concrete type, or use ConstructUsing((s, ctx) => new Dest(...)) / As<Concrete>() for interface destinations.","Ensure the destination has a public parameterless constructor, or supply ctor arguments via ForCtorParam.","If using ConstructUsingServiceLocator, confirm the locator returns a non-null instance for that type."],"exampleFix":"// before\nvar config = new MapperConfiguration(c => c.CreateMap<ISource, DestInterface>()); // DestInterface is abstract\nvar dest = mapper.Map<DestInterface>(src); // throws: cannot create instance\n\n// after\nvar config = new MapperConfiguration(c => c.CreateMap<ISource, DestInterface>().As<ConcreteDest>());\nvar dest = mapper.Map<DestInterface>(src);","handlingStrategy":"validation","validationCode":"static bool IsActivatable(Type t) =>\n    !t.IsAbstract && !t.IsInterface && t.GetConstructor(Type.EmptyTypes) != null;\n\nif (!IsActivatable(typeof(TDest))\n    && configuration.FindTypeMapFor<TSource, TDestination>()?.CustomCtorExpression == null\n    && serviceCtor(typeof(TDest)) == null)\n{\n    throw new InvalidOperationException($\"No way to create {typeof(TDest)}. Register it or use ConstructUsing.\");\n}\n\nvar dest = mapper.Map<TDest>(source);","typeGuard":"static bool CanConstructDestination<TDest>(IServiceProvider sp) =>\n    !typeof(TDest).IsAbstract && !typeof(TDest).IsInterface\n    && (typeof(TDest).GetConstructor(Type.EmptyTypes) != null\n        || sp.GetService(typeof(TDest)) != null);","tryCatchPattern":"try { dest = mapper.Map<TDest>(source); }\ncatch (AutoMapperMappingException ex) when (ex.Message.StartsWith(\"Cannot create an instance of type\"))\n{\n    // register the type with DI / add ConstructUsing / As<Concrete>, then retry\n}","preventionTips":["Register destinations, resolvers, and converters in DI when using ConstructUsingServiceLocator.","Avoid mapping directly to interfaces/abstract classes; use As<Concrete> or ConstructUsing.","Guard resolvers that need injected dependencies by registering them explicitly."],"tags":["ioc","service-locator","instantiation","dependency-injection"],"backgroundTag":null,"analyzedSha":"dfa6dd587c5854b4beee5934beb39ba6e9569b84","analyzedAt":"2026-08-13T19:56:33.518Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}