-
Notifications
You must be signed in to change notification settings - Fork 34
Func
The second way to add factories is to inject a Func<...,T>
to the type that needs to resolve new objects at runtime. As with the factory interface mechanism, automatic propagation of arguments is also handled.
However, as a Func
gives practically no discoverable information about the nature of the required arguments, it is recommended not to employ Func<T>
-injection unless it takes no arguments. (Even if it takes no arguments I personally think factory interfaces are a cleaner way to manage factories; while you do have to write a little more code, the improved readability vs a Func<T>
is worth the effort).
The following example illustrates what's involved in using Func<T>
-injection:
class Foo
{
readonly Func<Bar> barFactory;
public Foo(Func<Bar> barFactory)
{
this.barFactory = barFactory;
}
public void Do()
{
var bar = this.barFactory();
...
}
}
That’s all you have to do in this case; there is no need to create a special binding for Bar
as the inferring of the resolution strategy is automatically managed by the standard provider's implicit behavior.