Create a Custom Session Value Provider

by Preetha 2012-09-11 16:21:57

Custom Session Value Provider

All the built-in value providers implements the interface IValueProvider.
Use the following code

public interface IValueProvider
{
bool ContainsPrefix(string prefix);

ValueProviderResult GetValue(string key);
}

The ContainsPrefix method should return true if the value provider can provide value for that property name. The GetValue method returns the actual value for the property wrapped as ValueProviderResult.

So here is our custom session value provider, quite simple

public class SessionValueProvider: IValueProvider
{
public bool ContainsPrefix(string prefix)
{
return HttpContext.Current.Session[prefix] != null;
}

public ValueProviderResult GetValue(string key)
{
return new ValueProviderResult(HttpContext.Current.Session[key],
HttpContext.Current.Session[key].ToString(), CultureInfo.CurrentCulture);
}
}

How we can use our SessionValueProvider? The answer is we need a factory for that.
Collapse | Copy Code

public class SessionValueProviderFactory : ValueProviderFactory
{
public override IValueProvider GetValueProvider
(ControllerContext controllerContext)
{
return new SessionValueProvider();
}
}

Now all we have to do is register the factory in Global.asax.cs.
Collapse | Copy Code

ValueProviderFactories.Factories.Add(new SessionValueProviderFactory());

If you have a model like,
Collapse | Copy Code

public class UserModel
{
public string AccountNo { get; set; }
...
}

and an action that expects this model,
Collapse | Copy Code

public ViewResult SomeAction(UserModel userModel,)
{
...
}

Also if you have the AccountNo stored in session as,
Collapse | Copy Code

Session["AccountNo"] = "X8w237jd923"

Our SessionValueProvider fills the userModel.AccountNo with the value from the session. Yes it is. The SessionValueProvider even helps us to avoid the dependency between Session in controller actions and that simplifies the unit testing. You can even think about value providers that feeds data to models from configuration or other strange places.

Tagged in:

817
like
0
dislike
0
mail
flag

You must LOGIN to add comments