Skip to content

Instantly share code, notes, and snippets.

@mikehadlow
Created October 12, 2010 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehadlow/622123 to your computer and use it in GitHub Desktop.
Save mikehadlow/622123 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using Castle.MicroKernel.Registration;
using Castle.Windsor;
namespace Mike.Spikes
{
public class CanResolveByGenericTypeConstraints
{
public void Spike()
{
var container = new WindsorContainer().Register(
Component.For(typeof(IRepository<>)).ImplementedBy(typeof(DefaultRepository<>)),
Component.For(typeof(IRepository<>)).ImplementedBy(typeof(OrderableRepository<>))
);
// this works as expected, the BasicThings are output in the order they are created.
var basicThingRepository = container.Resolve<IRepository<BasicThing>>();
Console.WriteLine("basic things");
Write(basicThingRepository.GetAll());
// it would be really nice if Windsor understood generic type constraints so that it returned
// an OrderableRepository<T> here instead of DefaultRepository<T>.
// Since OrderableThing implements IOrderable it can be satisfy the constraints of OrderableRepository<T>
var orderableThingRepository = container.Resolve<IRepository<OrderableThing>>();
Console.WriteLine("orderable things");
Write(orderableThingRepository.GetAll());
// would expect the entities to be output in reverse Id order
}
public void Write(IEnumerable<IEntity> items)
{
foreach (var item in items)
{
Console.WriteLine(item.Id);
}
}
}
public interface IEntity
{
int Id { get; set; }
}
public interface IOrderable
{
int Position { get; }
}
public interface IRepository<T> where T : IEntity
{
IEnumerable<T> GetAll();
}
public class DefaultRepository<T> : IRepository<T> where T : IEntity, new()
{
public virtual IEnumerable<T> GetAll()
{
return Enumerable.Range(0, 4).Select(id => new T {Id = id});
}
}
public class OrderableRepository<T> : DefaultRepository<T> where T : IEntity, IOrderable, new()
{
public override IEnumerable<T> GetAll()
{
return base.GetAll().OrderBy(entity => entity.Position);
}
}
public class BasicThing : IEntity
{
public int Id { get; set; }
}
public class OrderableThing : IEntity, IOrderable
{
public int Id { get; set; }
public int Position
{
get { return 10 - Id; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment