RFC: Is a supplied factory method useful for an IoC container?
June 10, 2009 by Daniel HoelblingI 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
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.