How to get a page in EPiServer 7

Denna artikel har migrerats från en tidigare version av vår webbplats och kan därför avvika i utseende och funktionalitet.

Den här artikeln är inte översatt till svenska och visas därför på engelska istället.


I’ve gotten a few questions about DataFactory in EPiServer 7, or rather about what to use instead of DataFactory. Hopefully this post will clarify how we get pages and blocks in EPiServer 7.

Uppskattad lästid : 2 minuter

Gå till avsnitt

Getting a page or block in EPiServer 7

// Get the equivalent of DataFactory in CMS 5/6
var repository = ServiceLocator.Current.GetInstance<IContentRepository>();

// Get content (page or block) with ID 5
var contentReference = new ContentReference(5);

// Get the page (or block)
return repository.Get<MyContentType>(contentReference);

Let’s say we have a start page type called StartPage. To get the start page we simply:

// Get the start page
var startPage = repository.Get<StartPage>(PageReference.StartPage);

DataFactory in EPiServer 7

The original Alloy Templates used DataFactory quite extensively. That’s partly because it was based on web forms and unit testing (or any other testing, for that matter) wasn’t much of a concern.

With ASP.NET MVC unit testing becomes a lot more feasible in practice, and so making your code testable makes more sense.

So, although DataFactory is still available in EPiServer 7 just as it was in EPiServer 6 and earlier versions, the preferred approach nowadays is to make use of the dependency resolver ServiceLocator class to get an instance of IContentRepository.

DataFactory in fact implements the IContentRepository interface, so you will likely be using it implicitly quite a lot regardless.

If you want more details you should read Johan Björnfot’s post on DataFactory and IContentRepository.