views:

49

answers:

1

Is there a way using IoC, MEF [Imports], or another DI solution to compose dependencies on the fly at object creation time instead of during composition time?

Here's my current thought. If you have an instance of an object that raises events, but you are not creating the object once and saving it in memory, you have to register the event handlers every time the object is created. As far as I can tell, most IoC containers require you to register all of the classes used in composition and call Compose() to make it hook up all the dependencies.

I think this may be horrible design (I'm dealing with a legacy system here) to do this due to the overhead of object creation, dependency injection, etc... but I was wondering if it was possible using one of the emergent IoC technologies.

Maybe I have some terminology mixed up, but my goal is to avoid writing a framework to "hook up all the events" on an instance of an object, and use something like MEF to [Export] handlers (dependencies) that adhere to a very specific interface and [ImportMany] them into an object instance so my exports get called if the assemblies are there when the application starts. So maybe all of the objects could still be composed when the application starts, but I want the system to find and call all of them as the object is created and destroyed.

+2  A: 

Typically the way you handle on-the-fly instantiation in a DI/IoC environment is to use abstract factories. The factory is the only type of class allowed to interact directly with the container, in order to resolve dependencies when instantiating a new object.

public interface IWidgetFactory
{
    IWidget CreateWidget(...);
}

public class MyIocWidgetFactory : IWidgetFactory
{
    private IoCContainer container;

    public MyIocWidgetFactory(IoCContainer container)
    {
        if (container == null)
            throw new ArgumentNullException("container");
        this.container = container;
    }

    public IWidget CreateWidget(...)
    {
        // Assumes that the container is configured to create transient objects
        // for IWidget, not a singleton.
        return container.Resolve<IWidget>();
    }
}

Please don't confuse this with the service locator anti-pattern; nothing else is allowed to touch the container, just the factory, and it only creates one type of object.

At this point, you just pass around the IWidgetFactory to whatever needs to create a widget at runtime. That's it - you've maintained DI.

Aaronaught
Some DI-containers also support generating factories for you. You you can inject for example a Func<IWidget>-delegate. The DI-container then generates a factory for IWidget-instances. For example in Autofac: http://nblumhardt.com/2010/01/the-relationship-zoo/
Gamlor