I have an interface to resolve and one of the mapped object’s dependencies has a property on it which I would like to set with a value that I only have available when I resolve the top level object.
There’s no valid default value for the property. If its not set it should be null and it should only be set if the value that I have available at resolve time is not null.
Is this conditional property injection possible?
I tried this…
container.RegisterType<ProductInstanceValidatorBase, CartItemPurchaseTypeValidator>("CartItemPurchaseTypeValidator", new InjectionProperty("AccountEntity", null);
… but it said I couldn’t use a null value!
I also tried this on the resolve…
container.Resolve<ProductInstanceValidatorBase>(new PropertyOverride("AccountEntity", value));
…but this throws an exception when the value is null. It says,
Parameter type inference does not work for null values. Indicate the parameter type explicitly using a properly configured instance of the InjectionParameter or InjectionParameter classes.
Parameter name: parameterValue
Basically I’m looking to register a property that is only set with an override and then only if the override value is non-null. Any ideas? Surely from a semantic point of view, property injection should be optional.
Cheers, Ian.
One potential fix to this problem is to implement a Null Object Pattern and pass
Account.Emptywhen you haven’t got a valid account. Here is what a class could look like:This way the account is never
nulland Entity framework wouldn’t complain.However I sense that you might have a larger problem with the design of the system. IoC container allows a more loosely coupled system, where the wiring of the components is defined before the program is run, not while it’s run. Judging by the name,
AccountEnyityis an entity class, not a service class, and you normally do not register entities with the IoC container, only services.In the light of the above I would suggest that
AccountEntityshouldn’t be an injectable property, but instead a normal property. You then externalize theProductInstanceValidatorBasecreation into a factory and let it take care of settingAccountEntitypropertyYou don’t even need to register
ProductInstanceValidatorBasewith Unity, but instead register the factory. This is how using the factory would look like: