Hi there,
It says in the Unity manual...
ParameterOverride can be used only for constructors.
So why are the parameters of methods left out?
Cheers, Ian.
Hi there,
It says in the Unity manual...
ParameterOverride can be used only for constructors.
So why are the parameters of methods left out?
Cheers, Ian.
In DI frameworks, we usually have constructor injection or property injection.
Constructor injection is when the framework constructing instances and automatically supplies instances matching the parameters of a constructor.
Property injection is when, after the instance is created, any property, with a type supported by the container, is automatically set to an instance of that type.
Parameters are usually not supported with properties, thus PropertyOverride
only makes sense with constructor injection.
Update: method injection in Unity allows a method to be called on the instance passing in parameters to the method call:
container.RegisterType<DriveController>(
new InjectionMethod("InitializeMe", 42.0,
new ResolvedParameter<ILogger>("SpecialLogger")));
The InjectionMethod
class forces you to provide values for all the methods parameters. Using a ParameterOverride
does not make much sense in this case since we already have provided explicit values for the resolver to use.
Note: a technical reason to why ParameterOverride
only works with constructor parameters is that supporting overrides for methods have some problematic cases. Consider the following class:
public class Foo
{
public Foo(IService service) { ... }
public void Initialize(IService service) { ... }
}
container.Resolve<IFoo>(new ParameterOverride("service", new Service()));
Which parameter should be overridden?
If you need to provide parameter values when resolving, I would suggest using factory delegates instead. Converting the sample above:
container.RegisterInstance<Func<int, DriveController>>(
number => {
var dc = new DriveController();
dc.InitializeMe(number, container.Resolve<ILogger>("SpecialLogger"));
return dc;
});
var factory = container.Resolve<Func<int, DriveController>>();
var dc = factory(42);
I have not tried this with Unity. I assume it will work, at least it shows that there should be alternatives to providing parameter values at "resolve time".
The reason I left it out, quite honestly, was development & test time, plus the fact that method injection is used much, much less than constructor or property injection. In particular, our test and doc teams were holding on by their fingernails trying to keep up with the stuff I was throwing them as it was.
There's no technical reason to leave it out. The Override objects are extensible, so it's perfectly reasonable to create your own to override method parameter values if you really need it.