What Is The DictionaryAdapter?
The DictionaryAdapter is a tool for runtime generation of typed wrappers around dictionaries, using a predefined interface declaration.
The most obvious use is to wrap the ASP.NET Session object, or MonoRail's PropertyBag/Flash. You can also use that to access your AppSettings from config file, and any other dictionary.
Using The DictionaryAdapter
First, create the interface:
public interface IUserAware { User CurrentUser { get; set; } bool IsLoggedIn { get; set; } }
Now you can create the wrapper:
IDictionaryAdapterFactory dictionaryAdapterFactory = new DictionaryAdapterFactory(); IUserAware session = dictionaryAdapterFactory.GetAdapter<IUserAware>(Session); if (session.IsLoggedIn) Response.Write(session.CurrentUser.Name);
Using a Generic Base Class For MonoRail Controllers
When using MonoRail, you'd probably want to use generic base classes for your controllers, that would help in creation of the wrappers:
public class WithWrappersController<IViewAdapter> : SmartDispatcherController { private IViewAdapter typedFlash; private IViewAdapter typedPropertyBag; protected IDictionaryAdapterFactory dictionaryAdapterFactory; protected override void Initialize() { base.Initialize(); dictionaryAdapterFactory = new DictionaryAdapterFactory(); } protected IViewAdapter TypedFlash { get { if (typedFlash == null) typedFlash = dictionaryAdapterFactory.GetAdapter<IViewAdapter>(Flash); return typedFlash; } } protected IViewAdapter TypedPropertyBag { get { if (typedPropertyBag == null) typedPropertyBag = dictionaryAdapterFactory.GetAdapter<IViewAdapter>(PropertyBag); return typedPropertyBag; } } } public class WithWrappersController<IViewAdapter , ISessionAdapter> : WithWrappersController<IViewAdapter> { private ISessionAdapter typedSession; protected ISessionAdapter TypedSession { get { if (typedSession == null) typedSession = dictionaryAdapterFactory.GetAdapter<ISessionAdapter>(Session); return typedSession; } } }
And you can use it, like that:
public class CarsController : WithWrappersController<IViewCars, IUserAware> { public void Index() { if (TypedSession.IsLoggedIn) { TypedPropertyBag.Message = "Hello " + TypedSession.CurrentUser.Name; } } public void Save([DataBind("car")]Car car) { if (HasValidationErrors(car)) { TypedFlash.Car = car; RedirectToRefferer(); return } } public void Edit(int carId) { if (TypedFlash.Car == null) TypedPropertyBag.Car = GetCar(carId); } }
