Different DataLoaders for the same ModelItem?

Aug 21, 2011 at 12:45 PM

I need to be able to specify different DataLoaders for different ModelItem Ids. An example of this would be I'd want to pull weather data from different providers (different uri & return format), one for each country. My initial thought was to pass the DataLoader (type) to DataManager's Load method, but the only way seems to be using the (static) attribute on ModelItem.

My current workaround is pass an additional parameter to the LoadContext (on Load), then extract that on both GetLoadRequest and Deserialize DataLoader methods and call appropriate classes based on that. Still, the code would be clearer if I could simply pass (or associate) a specific DataLoader with a ModelItem Id.

Any other way to do that?

Aug 24, 2011 at 6:24 AM

Hi -

Good question, and your current method is about right.  AgFx expects that a given Model/Loader combo gets its data from a single source.

There's lots of ways you could optimize this - you could have a SwitchingDataLoader thing that expects a LoadContext with a "LoaderType" property, and so what it does is looks at that property, creates the appropriate derived loader type, and delegates to that.  It's pretty close to what you're doing, but if you encounter this case a lot, it would make it very easy.


[pseudo code...]

public class SwitchingLoadContext : LoadContext {

	public SwitchingLoadContext(object id, Type loaderType) {}

	public Type LoaderType {};


public class SwitchingDataLoader : IDataLoader<SwitchingLoadContext> {

	protected IDataLoader<T> GetLoader<SwitchingLoadContext>(T context) {

			// needs caching, error checking, etc.

			IDataLoader<T> loader = Activator.CreateInstance(context.LoaderType) as IDataLoader<T>;

			return loader;


	public LoadRequest GetLoadRequest(SwitchingLoadContext context, Type objectType) {

			var loader = GetLoader(context);

			return loader.GetLoadRequest(context, objectType);



There's a few tweaks you can do to this but it's basically the idea.  Another model would be to have a different derived ViewModel type for each service you're going to use and to use the objectType property to figure it out, but probably not as nice.

Hope that helps!

Aug 24, 2011 at 6:43 AM

Ah yes, makes perfect sense! Makes the code a lot more clean too. Thanks!