Search And Destroy

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

Archive for the ‘IoC’ Category

IoC : Leaking the Functional Mindset into Imperative Languages

Posted by kilfour on August 2, 2010

In functional languages, functions are referentially transparant.
Meaning if I provide the same parameters to a function each time I call it, it will return me the same result, no matter how many times I call it, and no matter when.

I’m sure the developers amongst you with a TDD mindset can see the advantage of this.

Several things in an everyday application don’t actually work that way.
SomeRepository.GetAllThings() f.i.
It is obvious that this will not return the same result each time, as it is depending on the state of the repository/database.

However, most classes consuming these ‘classes-with-side-effects’ _are_ referentially transparant.

IoC allows us to easily abstract away these annoying side-effects-inducing bits of the application and write some solid (and easily maintainable) unit tests for the code that is actually delivering business value.

Kind ‘a like monads really ;-) .

Posted in IoC, Rants | Leave a Comment »

The Spoon Does Not Exist !

Posted by kilfour on July 15, 2010

I believe in the strength of having a system metaphor.

Krzysztof Kozmic has introduced me to a metaphor for inversion of control, which he calls the Matrix Principle.

Call me a hippie, but through everyday usage, I have found this to be a very powerfull image.
I have actually murmured to myself : “the spoon does not exist”, on more than one occasion whilst refactoring my IoC code…

Posted in IoC | Leave a Comment »

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 »

IoC or Currying, Both are Just Dancing with Objects

Posted by kilfour on May 29, 2010

Elaborating on my previous post

Currying means you can break down any operation into a set of functions defined by exactly one input parameter and exactly one output parameter.
Binary functions are broken down like so, f.i. :
function Plus a = a +
then
function Addition a b = (Plus(a))(b)
This ofcourse means passing functions around as first-order objects, which should not be a secret to the C# 3.5 dev.

This pattern allows for some powerfull glueing together of pieces of code and in my opinion has a lot to do with the concise nature of functional languages.

IoC Containers do the same thing.

In Haskell getting this stuff right has a lot to do with satisfying the type system.
It takes me ages to get it working.
Everytime.
Once the ‘ken thing compiles it works fine without run-time errors and the code used is always rediculously concise.

Using an IoC it’s up to you to wire it correctly, your program will always compile, but you’ll get run-time errors if you forgot something.
You might even get weird errors if you’ve messed up your lifestyle(s).
But if you do get it right, the amount of infrastructure code you remove, is of the same magnitude that you get for free in functional languages.

The end result is the same :

Blocks of execution that take one(*) free parameter and have all their fixed parameters filled in, be it through currying or through IoC.

A powerfull new glue.

(*) : … or more, but that’s a code smell…

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

 
Follow

Get every new post delivered to your Inbox.