Showing newest posts with label Castle. Show older posts
Showing newest posts with label Castle. Show older posts

Tuesday, October 7, 2008

Register services in Windsor - take 2

I had to write my Find service method in almost every solution I made so it was time to add it to Castle. Now you can write this to auto register all your services, repositories, views, etc:

[TestFixture]
public class AllTypesTestCase
{
[Test]
public void Should_register_by_service_interface()
{
var kernel = new DefaultKernel();
kernel.Register(AllTypes
.Of<IService>()
.FromAssembly(typeof(ProductService).Assembly)
.WithService.FromInterface());

Assert.AreEqual(typeof(ProductService), kernel.Resolve<IProductService>().GetType());
Assert.AreEqual(typeof(OrderService), kernel.Resolve<IOrderService>().GetType());
}
}

public interface IService
{
}

public interface IProductService : IService
{
}

public class ProductService : IProductService
{
}

public interface IOrderService : IService
{
}

public class OrderService : IOrderService
{
}

Thanks Craig Neuwirt for applying my patch (with some modifications) to Castle.

Thursday, October 2, 2008

Register services in Windsor

This code handles almost all your future Windsor components. Very nice in my opinion!

protected virtual void InitializeWindsor()
{
if (container == null)
{
container = new WindsorContainer();

ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container));

//register all services
container.Register(
AllTypes.FromAssembly(typeof (ProductService).Assembly)
.BasedOn<IService>()
.WithService.Select(type => FindService(type, typeof (IService))));

//register all repositories
container.Register(
AllTypes.FromAssembly(typeof (ProductRepository).Assembly)
.BasedOn<IRepository>()
.WithService.Select(type => FindService(type, typeof (IRepository))));

//and so on...
}
}

private static Type FindService(Type type, Type implements)
{
return FindService(type, implements, new Type[0]);
}

private static Type FindService(Type type, Type implements, ICollection<Type> typesToIgnore)
{
Type first = null;
Type[] interfaces = type.GetInterfaces();
foreach (Type theInterface in interfaces)
{
if (theInterface.GetInterface(implements.FullName) != null && !typesToIgnore.Contains(theInterface))
{
first = theInterface;
break;
}
}
return first;
}

The alternative is this. But this one doesn't handle future components and you have to register them one by one.

protected virtual void InitializeWindsor()
{
if (container == null)
{
container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory(Container));

// Register all services
container.Register(
Component
.For<IProductService>()
.ImplementedBy<ProductService>());

container.Register(
Component
.For<IOrderService>()
.ImplementedBy<OrderService>());

// continue with all other services, repositories, etc..
}
}