Skip to content

Optional dependency resolution #236

@ENikS

Description

@ENikS

Optimizing Optional Dependency resolution

Traditionally, when resolving OptionalDependency unity would execute the following code:

try
{
    return context.Resolve(type, Name);
}
catch (Exception ex)
{
    return null;
}

Exception as flow control

As everyone knows, using exception mechanism for controlling execution flow is wrong. It is quite expensive as well. If normal if/else statements take few nanoseconds to execute, exception handling takes microseconds!

Assigning default value

Optional dependencies are either evaluated to resolved value or default (usually null) if resolution is unsuccessful.

This assignment is either redundant if initialized member already default or incorrect if member is initialized with default value. Consider the following example:

public class SomeType
{
    [OptionalDependency] 
    public int Field = 10;

    [OptionalDependency] 
    public string Property { get; set; } = "DefaultString";    

    [InjectionMethod]
    public void Method([OptionalDependency("Name")] int value = 33) {}
}

Each of these members, Field, Property, and parameter value have some value assigned during design time. Setting it with default in case dependency resolution fails is incorrect. It should be left as is and only reassigned if dependency successfully resolved.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions