Skip to content

Instantly share code, notes, and snippets.

@jeremydmiller
Created April 4, 2011 13:28
Show Gist options
  • Save jeremydmiller/901627 to your computer and use it in GitHub Desktop.
Save jeremydmiller/901627 to your computer and use it in GitHub Desktop.
Greasing the generic wheel
// Extension method in FubuCore
public static T CloseAndBuildAs<T>(this Type openType, params Type[] parameterTypes)
{
var closedType = openType.MakeGenericType(parameterTypes);
return (T) Activator.CreateInstance(closedType);
}
// Ahem, uncompleted spike somewhere in FubuMVC I need to strip out or finish...
public class ProjectionFactory : IProjectionFactory
{
private readonly IEnumerable<IProjectionSource> _sources;
public ProjectionFactory(IEnumerable<IProjectionSource> sources)
{
_sources = sources;
}
public IProjection ProjectionFor(Type type)
{
var builder = typeof (Builder<>).CloseAndBuildAs<IBuilder>(type);
return builder.Build(_sources);
}
public IProjection ProjectionFor(Type type, string name)
{
var builder = typeof (Builder<>).CloseAndBuildAs<IBuilder>(type);
return builder.Build(_sources, name);
}
public class Builder<T> : IBuilder
{
public IProjection Build(IEnumerable<IProjectionSource> sources)
{
var values = sources.SelectMany(x => x.ValueProjectionsFor<T>());
return new Projection<T>(values);
}
public IProjection Build(IEnumerable<IProjectionSource> sources, string name)
{
var values = sources.SelectMany(x => x.ValueProjectionsFor<T>(name));
return new Projection<T>(values);
}
}
public interface IBuilder
{
IProjection Build(IEnumerable<IProjectionSource> sources);
IProjection Build(IEnumerable<IProjectionSource> sources, string name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment