In this post, you will learn how to apply a visitor group in code within an Episerver CMS powered website. If you are not quite sure what a visitor group is, think of personalization and segmentation. Episerver provides developers with several ways to interact with visitor groups. in this tutorial, you will learn how to master all of them. If you want to add segmentation to your website, read on 🔥🔥🔥
In this tutorial, I assume you have some previous knowledge of visitor groups. If you need a refresher I recommend reading this
VisitorGroupHelper
One way to access visitor groups within Episerver is to use the VisitorGroupHelper
which is found within the EPiServer.Personalization.VisitorGroups
namespace. This helper will check if the current user matches a certain visitor group. The code to do this match is shown below:
This helper is useful when you want to check if a user should be segmented, however, that's pretty much all we can do with it. This is why in most instances you will be working with IVisitorGroupRepository
IVisitorGroupRepository
IVisitorGroupRepository
provides access to standard functions like, saving a visitor group, deleting a visitor group, listing all visitor groups and loading an individual visitor group by Id. To create and save a visitor group we need to use the IVisitorGroupRepository
with a VisitorGroup
object:
You can access IVisitorGroupRepository
using dependency injection. In this example, I use the anti-pattern ServiceLocator
technique for simplicity. On Line2, I create a VisitorGroup
and then use the Save()
method to store the details within the Episerver database:
In order for a visitor group to do something useful, you need to associate a criterion with a visitor group. A group that has no segmentation logic is not that useful 😕 To create and apply criteria you will need to use another API, `IVisitorGroupCriterionRepository.
IVisitorGroupCriterionRepository
In order to add criterion, you have to use IVisitorGroupCriterionRepository
. If you try to create a criterion directly, you will encounter an Object Reference exception. Luckily, the IVisitorGroupCriterionRepository
is pretty easy to use:
IVisitorGroupCriterionRepository
only exposes one method, the list method. This method gets all the visitor groups that have been defined in your solution. You can then use the TypeName
property to return the criterion that you care about. With a reference to the criterion, you can then associate it with a visitor group:
This is all the code you need to create a visitor group in code. Using a combination of IVisitorGroupRepository
and IVisitorGroupCriterionRepository
repositories makes life easy. Happy Coding 🤘