jeudi 17 décembre 2015

Lists, Interfaces and Objects

I've a requirement for a custom list.

I've defined its interface like this...

public interface IMyList: IList<IMyListItem>
{
    // Stuff
}

and the concrete class is defined like this ...

public class MyList : List<IMyListItem>, IMyList
{

}

All is good.

Until, I try and deserialize something into an instance of MyList. When I do that using something like this ...

var result = JsonConvert.DeserializeObject<MyList>(someString)

JSon.NET complains with this message...

Message=Could not create an instance of type IMyListItem. Type is an interface or abstract class and cannot be instantiated.

I get what the message is telling me, but I can't work out what do do with my class and interface definitions.

I could change the definition of MyList to public class MyList : List<MyListItem> but then the interface is dependent on a concrete class and, more importantly for me, it creates a circular reference (my Models and the interfaces that define them are in separate assemblies).

Am I just doing it wrong? It it not reasonable to have the Interfaces and Class implementations in different assemblies? Is there a technique/pattern that I should be using for this that I'm not?

Aucun commentaire:

Enregistrer un commentaire