On most projects, there will be a requirement for users to select more options out of a dropdown list or a checkout. In Episerver this is done via a selection factory, more information can be found here.  

Like the good developers we are, when we're building our websites we want to stick to the DRY principle (don't repeat yourself) and we don't want to have to create a new selection factory class every time that we want to display different data.  The best way to prevent having to write all this duplicate code is to pass a parameter into the selection factory and then change the data source of the factory based on the parameter.

How Do I Pass A Parameter Into A Selection Factory?

First, let's look at the code to set a selection factor on a property.

As we pass a type into the selection factory, then it's not quite as simple as passing a string, or enum in via the selection factory. If we look at the selection factory code:

GetSelections() is the method Episerver calls when it tries to get the data. The input parameter is an ExtendedMetadata. If you look in here you can see that it contains a property called Attributes. This is the way that we can pass information from our class/block definitions into the selection factory. We create a custom attribute, declare it on the same property we want to set as a selectionfactory. When the selection factory gets called, we then read the contents of that attribute. So let's dig into some code:

Our property declaration now looks like this:

Our selection factory code will now look something like this:

Passing parameters is possible when you use a selection factory, however, the way you need to do it isn't that obvious. When you want to pass in a parameter, all you need to do is via custom attributes, rather than directly through the selection factories constructor. Enjoy!