Search And Destroy

Look out honey, ’cause I’m using technology!

Archive for the ‘Castle’ Category

OneReferencePerThread

Posted by kilfour on July 7, 2010

It is now wednesday evening, … and I know.
Overshooting my estimate by two days.
I think it’s a component burden issue.

I have been using Castle.Windsor quite a lot lately, because I really like the way it allows the imperative programmer to use functional constructs.

I have been pushing the container to the limit, and surprisingly enough, it has never let me down.
The more I learned, the more code I could remove.
The more I demanded, the more it delivered, and there was even more (infrastructure/implementation) code I could remove.
Making the whole model much more declarative and reusable.

Today it let me down.

It’s still my favourite dotnet lib ever though.

[Fact]
public void StrangeSingleCallToRelease()
{
    IWindsorContainer container =
        new WindsorContainer()
            .Register(Component.For<MyComponent>()
                          .LifeStyle.Custom<SingletonLifestyleManagerSpy>());

    var componentOne = container.Resolve<MyComponent>();
    var componentTwo = container.Resolve<MyComponent>();

    Assert.Equal(componentOne, componentTwo);
    Assert.Equal(2, SingletonLifestyleManagerSpy.TimesResolved);

    container.Release(componentOne);
    Assert.Equal(1, SingletonLifestyleManagerSpy.TimesReleased); 
    
    container.Release(componentTwo);
    Assert.Equal(1, SingletonLifestyleManagerSpy.TimesReleased); 
}

I don’t get this without looking at the Castle.Windsor code.
The boolean returned by the lifestyle managers resolve function seems to serve as a guard for not destroying the components any singleton (or perwebrequest and the likes) depends on.
Still, very implicit behaviour.
Not sure if it would affect performance much, but if this boolean could serve the purpose of not removing the instance from the ReleasePolicy’s (component-) Burden collection, I reckon it would lead to a much more intuitive API.

And my naive implementation, mentioned above, would work ;-)

I do have a workaround, but its rear-end-ugly.

Any thoughts ?

Posted in Castle, IoC | Leave a Comment »

OneReferencePerThreadLifestyleManager

Posted by kilfour on July 2, 2010

Here’s a Castle.Windsor custom lifestyle which might turn out to be quite usefull :

public class Ref
{
    public int RefCount;
    public object Target;
}

public class OneReferencePerThreadLifestyleManager : AbstractLifestyleManager
{
    private readonly Dictionary<long, Ref> references = new Dictionary<long, Ref>();
    private static long Key() { return Thread.CurrentThread.ManagedThreadId; }

    public override object Resolve(CreationContext context)
    {
        if (!references.ContainsKey(Key()))
            references.Add(Key(), new Ref());
        Ref reference = references[Key()];
        if (reference.RefCount == 0)
            reference.Target = base.Resolve(context);
        reference.RefCount++;
        return reference.Target;
    }

    public override bool Release(object instance)
    {
        Ref reference = references[Key()];
        reference.RefCount--;
        if (reference.RefCount == 0)
        {
            reference.Target = null;
            references.Remove(Key());
            return base.Release(instance);
        }
        return false;
    }

    public override void Dispose()
    {
        references.ForEach(kv => Kernel.ReleaseComponent(kv.Value.Target));
    }
}

Or it might turn out to be a much too naive implementation…

I’ll know monday evening ;-)

Posted in C# Musings, Castle, IoC | Leave a Comment »

Checking Stuff Out

Posted by kilfour on June 5, 2010

Adding a validation :

public class ProductPeriodValidation : Validation<Product>
{
    public override bool IsValid(Product instance)
    {
        return instance.BeginDate  < instance.EndDate;
    }

    public override string Message(Product entity)
    {
        return String.Format(
            "Error : Begin Date must be smaller than End Date. ProductCode : {0}.",
            entity.ProductCode);
    }
}

Using a validator :
public class ProductImporter : Importer<HashedSet<Product>>, IProductImporter
{
    ...	

    private readonly ICollectionValidator<Product> productValidator;

    public ProductImporter(
    	...,
        ICollectionValidator<Product> productValidator)
        : base(...)
    {
        this.productValidator = productValidator;
    }

    protected override HashedSet<Product> ValidateExtract(HashedSet<Product> products)
    {
        productValidator.Validate(products);
        return products;
    }
    
    ...
}

Register it all in the container and wire it up :
Container.AddFacility<ValidationFacility<Product>>();

Posted in C# Musings, Castle, Checking Stuff Out, IoC | Leave a Comment »

Checking Stuff Out : ValidationFacility

Posted by kilfour on June 5, 2010

public class ValidationFacility<TValidationTarget> : AbstractFacility
{
    protected override void Init()
    {
        Kernel.Register(
            Component.For<ValidationLookup<TValidationTarget>>()
                .LifeStyle.Singleton);

        Kernel.Register(
            Component.For<ICollectionValidator<TValidationTarget>>()
                .ImplementedBy<CastleCollectionValidator<TValidationTarget>>()
                .LifeStyle.Singleton);

        Kernel.Register(
            Component.For<IValidator<TValidationTarget>>()
                .ImplementedBy<CastleValidator<TValidationTarget>>()
                .LifeStyle.Singleton);

        Kernel.Register(
            AllTypes
                .FromAssembly(typeof(TValidationTarget).Assembly)
                .BasedOn(typeof(IValidation<TValidationTarget>))
                .Configure(c => c.LifeStyle.Transient)
                .WithService
                .FromInterface(typeof(IValidation<TValidationTarget>)));
    }
}

Posted in C# Musings, Castle, Checking Stuff Out, IoC | Leave a Comment »

Checking Stuff Out : CastleCollectionValidator

Posted by kilfour on June 5, 2010

public class CastleCollectionValidator<TInstance> : CollectionValidator<TInstance>
{
    private readonly ValidationLookup<TInstance> lookup;
    public CastleCollectionValidator(ValidationLookup<TInstance> lookup)  
    {
        this.lookup = lookup; 
    }

    public override IEnumerable<IValidation<TInstance>> GetValidations()
    {
        return lookup.GetValidationsFromKernel();
    }
}

Posted in C# Musings, Castle, Checking Stuff Out, IoC | Leave a Comment »

Checking Stuff Out : ValidationLookup

Posted by kilfour on June 5, 2010

public class ValidationLookup<TInstance>
{
    private readonly IKernel kernel;

    public ValidationLookup(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public IEnumerable<IValidation<TInstance>> GetValidationsFromKernel()
    {
        return
            kernel
                .GetHandlers(typeof(IValidation<TInstance>))
                .Select(handler =>
                        ((IValidation<TInstance>)handler.Resolve(CreationContext.Empty)));
    }
}

Posted in C# Musings, Castle, Checking Stuff Out, IoC | Leave a Comment »

Checking Stuff Out : CastleValidator

Posted by kilfour on June 5, 2010

public class CastleValidator<TInstance> : Validator<TInstance>
{
    private readonly ValidationLookup<TInstance> lookup;
    public CastleValidator(ValidationLookup<TInstance> lookup)  
    {
        this.lookup = lookup; 
    }

    public override IEnumerable<IValidation<TInstance>> GetValidations()
    {
        return lookup.GetValidationsFromKernel();
    }
}

Posted in C# Musings, Castle, Checking Stuff Out, IoC | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.