Unity’s [OptionalDependency] – don’t do it


Just a quick tip – when using Unity for DI – DON’T use the [OptionalDependency] attribute unless you absolutely have to.

Why? Because it can be incredibly unslow. I’ve not had a look at the source code so can’t know exactly, but as I recall, the way that Unity deals with OptionalDependencies when they are not available is by throwing an exception, which is then caught and supressed by itself.

Performance varies depending on the type of object and the number of constructors it has (among other things), but, for example, missing Strings that are marked optional are incredibly slow if not available – sometimes upto 50x slower to construct an object.

This might not be noticeable if you just create the odd object here and there – but if you start doing anything heavyweight, you’ll soon notice it – so avoid it wherever possible.

4 thoughts on “Unity’s [OptionalDependency] – don’t do it

  1. Let’s take it a step further and say, don’t use Unity attributes at all. By using attributes, you are introducing a direct dependency on your IoC container throughout your codebase – not a great idea. Composing your container at your compositional root and injecting dependencies via the constructor is a far better approach. Truly optional dependencies are pretty rare, but property injection without using attributes is perfectly possible in these cases.

    1. Personally, I prefer Property-based injectors (which have the [Dependency] attribute on them); it eliminates the boilerplate of setting them in the constructor and makes it clear what your dependencies are. I know that that’s not what everyone likes though!

      I’m personally not fussed about putting that attribute on properties – I’ve yet to get to a project where I’ve changed IoC container midway through development…

Leave a comment