In Episerver 8 we have two API's available for us to allow fetching and modifying content. These are the IContentLoader and the IContentRepository. In today's guide, I'm going to cover how to do some basic API calls with Episerver and hopefully explain the difference between the two. This article is a follow on from How to get a page in EPiServer 7?
IContentLoader is the basic API that should be used if you only ever need to do read operations. It implements methods such as Get<>, GetChildren<> and GetDescendants<>. To get a page from Episerver, you would use this code:
In this example, the Type being passed into the Get<> method is a custom class that you will need to define in your code. This type can be swapped out for any class that implements the IContent interface. More information about content, can be found in Different Ways Of Casting Objects From The Episerver Api A quick example of how a class definition for a PageType might look like, is shown below:
IContentRepository is the more beefy cousin of IContentLoader. IContentRepository provides the same functionality as IContentLoader and also allows us to do exciting things like.. saving and deleting content... WOW :P In technical terms IContentRepository implements the IContentLoader interface, so anything you can do in IContentLoader you can also do in IContentRepository. IContentRepository works very similarly as IContentLoader, as seen here:
An example of saving content might then look like this:
Episerver provides several easy to use API's for us to work with content.. specifically IContentLoader and IContentRepository. When I write code, I tend to just use IContentRepository as you can never plan how the code base will grow over time. The IContentLoader API provides developers with a read-only way to talk to Episerver. You may want to only use this in your view model code for security, while the IContentRepository gives read and write access.