ContainerRegistration optimization
Registrations collection
Legacy Unity implemented Registrations collection as IEnumerable<ContainerRegistration> with ContainerRegistration being a class.
Unity v5 introduced interface IContainerRegistration and returned enumerable as IEnumerable<IContainerRegistration>. Under the hood this interface was implemented by ContainerRegistrationStruct structure. The struct was intended to eliminate extra allocations for ContainerRegistration classes.
Problem
The implementation did not produce desired 'zero memory allocation' as intended. In many cases the structure is still boxed into an object and passed as interface even in cases where this could be avoided.
ContainerRegistration struct
To solve this allocation problem Unity is dropping interface IContainerRegistration and introduces struct ContainerRegistration. The struct does not implement any interfaces and is not boxed implicitly on returns.
Boxing and null
This change is breaking in cases where return must be an object or interface. For example this used to work:
var parentRegistration = Container.Registrations
.Where(r => r.RegisteredType == typeof(ILogger))
.FirstOrDefault();
Assert.IsNull(parentRegistration);
Now being a struct, it is value type and by default is not null. To work correctly the struct must be boxed and returned as a reference. A simple fix would be to cast it into an object and force compiler to box it:
var parentRegistration = Container.Registrations
.Where(r => r.RegisteredType == typeof(ILogger))
.Cast<object>()
.FirstOrDefault();
Assert.IsNull(parentRegistration);
LifetimeMananger
Original Unity (v4.x) exposed two pieces of information about lifetime:
/// <summary>
/// The registered lifetime manager instance.
/// </summary>
public Type LifetimeManagerType { get; private set; }
/// <summary>
/// The lifetime manager for this registration.
/// </summary>
/// <remarks>
/// This property will be null if this registration is for an open generic.</remarks>
public LifetimeManager LifetimeManager { get; private set; }
Unity v5.x eliminated LifetimeManagerType as redundant. If you have a manager, you could always get its type.
LifetimeManager
In Unity v6 LifetimeManager takes a new role as a RegistrationManager in addition to managing lifetime. It stores all injected information and maintains state of the registration throughout lifetime of the manager.
This new development changes significance of the manager and makes entire container vulnerable to manager's integrity. To protect integrity of the system and eliminate possibility of corruption the manager will no longer be exposed by the registration collection. The container will only display Type of the manager but not the manager itself.
The new entry in Registrations collection will expose this property:
/// <summary>
/// The registered lifetime manager instance.
/// </summary>
public Type LifetimeManagerType { get; private set; }