Skip to content

Instantly share code, notes, and snippets.

@glennblock
Forked from kellabyte/webapi_experiment1.cs
Created April 11, 2012 00:44
Show Gist options
  • Save glennblock/2355987 to your computer and use it in GitHub Desktop.
Save glennblock/2355987 to your computer and use it in GitHub Desktop.
Web API ideas
//generic formatter which takes in a model and transforms it to something specific for the media type
//StrategyFormatter is a generic formatter that you derive from to create specific ones. You override the formatter methods to write the response.
public interface IFormatterStrategy<TOutput> {
TOutput Transform(object model);
}
//loops through all the formatter strategies and asks them to handle the model
public abstract class StrategyFormatter<TOutput> : MediaTypeFormatter {
public IEnumerable<IStrategyFormatter<TOutput>> Strategies {public get;private set;}
public StrategyFormatter(params IEnumerable<IFormatterStrategy<TOutput>> strategies) {
Strategies = strategies;
//implementation here
}
}
public class AtomFormatter(IEnumerable<IFormatterStrategy<AtomMediaTypeModel>> strategies[]) : StrategyFormatter<TOutput> {
//will take in a model and translate it into an AtomModel which will be written.
}
public class CustomerFormatterStrategy : IFormatterStrategy<AtomMediaTypeModel> {
public AtomMediaTypeModel Transform(Customer model)
{
//transform a customer to an Atom feed.
}
}
var formatter = new AtomFormatter(new CustomerFormatterStrategy());
@DrPizza
Copy link

DrPizza commented Apr 11, 2012

Some people, when confronted with a problem, think “I know, I’ll create an interface.” Now they have two problems.

@darrelmiller
Copy link

Don't worry, adding a generic parameter to the interface usually solves one of those problems.

@glennblock
Copy link
Author

DrPizza some people dismiss things with comments without seeking to understand the intention. I agree just adding an interface is not the solution. That is not the intent.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment