Dave's Blog

Latest Blog Entry

Could not create an instance of type (CosmosDb upsert)


April 23, 2021

When upserting a new entity to a Cosmosdb Database I was getting

Could not create an instance of type MyNamespace.IUser. 
Type is an interface or abstract class and cannot be instantiated. 
Path 'User.Name', line 1, position 213.

When using the CosmosDb nuget package you can't specify a custom serialiser as you can with, say, Newtonsoft.

Instead you can create a constructor which takes a concrete implementation of the interface

[JsonConstructor]
public MyEntity(Status status, SomeOtherType value, User user) : base(user)
{
        Status = status;
        Value = value;
}

where base(user) calls

public CosmosEntityBase(IUser user)
{
        User = user;
}
public IUser User { get; set; }     

This will be less straightforward if you have multiple implementations of the interface. You'll have to determine which one to instantiate.

However if the JsonConstructor has the interface IUser in its signature then

Could not create an instance of type MyNamespace.IUser. Type is an interface or abstract class and cannot be instantiated. Path 'User.Name', line 1, position 213.

will be returned so that is what you need to avoid.

About

Hi, I am .net developer, development manager and software craftsman in Manchester. This is a place to store my thoughts.

These thoughts, writings and opinions are mine and not my employers' or any previous employers'.