Tigraine

Daniel Hoelbling-Inzko talks about programming

RFC: Is a supplied factory method useful for an IoC container?

Posted by Daniel Hölbling on June 10, 2009

I need your help.
Does it make sense to have something like this in a DI container?

[Fact]
public void CanSupplyFactoryMethod()
{
    store.Register(
        p => p.Service<IService>()
                 .Factory(s => 
                     {
                         Console.WriteLine("Creating type..");
                         if (SOME_STATIC_VAR == true)
                         {
                             return new ClassWithNoDependencies();
                         }
                         return new OtherClass();
                     })
        );
    var service = container.Resolve<IService>();
    Assert.IsType<ClassWithNoDependencies>(service);
}

The idea being, you can supply a function delegate (Func<IPandoraContainer, T>) to be executed when the service should be instantiated. This would make a rather interesting extensibility story, since I’d avoid having to build in all kinds of hard to find hooks to allow modification of the object creation.

Also, I’d like this delegate to be evaluated during runtime. This could enable me to resolve to another object if for example a network link is down etc.

Another obvious use for this would be to access classes that are present in the .NET BCL but can’t be instantiated and would otherwise be supplied to the container through .Instance like the HttpContext:

store.Register(
    p => p.Service<HttpContext>()
        .Factory(s => { return HttpContext.Current; }));

What do you think? Should this make it into Pandora? What do you want to see in a DI container? Please feel free to comment.

comments powered by Disqus

My Photography business

Projects

dynamic css for .NET

Archives

more