Using Lazy<T>
property caching, is there any behavioural differences between accessing the property with a backing field or without the backing field? Perhaps any performance hits?
The example code below is caching Autofac IoC container in an internal property. The code is only meant to be initialized once. Whether it does or does not follow the right IoC / DI principles is not the question.
Example 1:
internal static ILifetimeScope Bootstrap = new Lazy<ILifetimeScope>(InitializeContainer, LazyThreadSafetyMode.ExecutionAndPublication).Value;
private static ILifetimeScope InitializeContainer()
{
ContainerBuilder builder = new ContainerBuilder();
//Registration logic...
return builder.Build();
}
Example 2:
private static readonly Lazy<ILifetimeScope> _container = new Lazy<ILifetimeScope>(InitializeContainer, LazyThreadSafetyMode.ExecutionAndPublication);
internal static ILifetimeScope Container => _container.Value;
private static ILifetimeScope InitializeContainer()
{
ContainerBuilder builder = new ContainerBuilder();
//Registration logic...
return builder.Build();
}
Edit 1 I'm mostly interested in having a cached value of the container, so that it doesn't get initialized each time i access the property. I don't care if the initialization is deferred.