1
votes

The short question:
Does Castle Windsor have something similar to Spring.Net's "Lookup Method Injection" that can be configured from XML, which provides the ability to fetch transient instances from the container without the class being aware of the IoC container?

The long question:
I'm a long time Spring/Spring.Net user and I have been experimenting with Castle Windsor, by trying to port a project over to it. Spring.Net has a concept of "Lookup Method Injection" which (from the Spring docs)...

Lookup method injection is the ability of the container to override methods on container managed objects, to return the result of looking up another named object in the container. The lookup typically involves a prototype object as in the scenario described in the preceding section. The Spring framework implements this method injection by a dynamically generating a subclass overriding the method using the classes in the System.Reflection.Emit namespace.

What this means is, If I had the following...

public class SomeTransient
{
    // ... I have dependencies that need to be filled by IoC container
}

public class SomeClass
{
    public virtual void Work()
    {
        var o = CreateTransient();
    }

    public virtual SomeTransient CreateTransient() { }
}

I can instruct Spring to override the CreateTransient method, and have that method return a new container created transient instance (with it's dependencies initialized) each time the method is called. The unique part of this is, it doesn't require direct links to the Spring Framework (eg. SomeClass doesn't have to implement a specific interface).

Is there something similar in Castle Windsor to accomplish this via XML?

(I will eventually move away from XML config, but at the moment I'm just trying to get it running)

1

1 Answers

2
votes

Castle has something better; Typed Factories. You can also inject even a delegate! http://stw.castleproject.org/Windsor.Typed-Factory-Facility-delegate-based-factories.ashx

It is better because it does not depend on dynamically generation code, and it looks much more cleaner.

It looks much more cleaner because the class doesn't depend on someone overriding that method. It is impossible to test this class without subclassing.

If you really want to do something like this, i would expect:

public abstract class SomeClass
{
  public abstract SomeTransient CreateTransient();
}

but... again it doesn't feel right.

Edit 2

Unity 2 support these kind of delegate factories; you can read more here: http://www.truewill.net/myblog/index.php/2010/05/06/unity_2_0_combining_injectionfactory_and

thanks to @eiximenis