Lazy<T>
속성 캐싱을 사용하는 경우 배킹 필드가 있거나 배킹 필드가없는 속성에 액세스 할 때 동작간에 차이가 있습니까? 아마도 어떤 연주가 들리는가?게으른 <T> 캐싱 백킹 필드 /없이 - 성능?
아래 예제 코드는 내부 속성에 Autofac IoC container을 캐싱합니다. 이 코드는 한 번만 초기화 할 수 있습니다. 그것이 올바른 IoC/DI 원칙을 따르 든 따르지 않는 것이 문제는 아닙니다.
예 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();
}
예 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();
}
편집 한 내가 있도록 용기의 캐시 값을 갖는에 주로 관심이 속성에 액세스 할 때마다 초기화되지 않습니다. 초기화가 지연되는지는 상관하지 않습니다.
"올바른 IoC/DI 원칙을 따르 든 따르지 않는 것은 문제가 아닙니다." 의문의 여지가 없지만 언제나 의문의 여지가있는 것. – Steven
별로. 두 예제 모두에서 속성에 액세스를 시도했으며 초기화 팩토리를 한 번만 실행하고 있는지 확인했습니다. 많은 'Lazy'캐싱 예제가 뒷받침 필드와 함께 표시되며, 첫 번째 예제가 더 예쁘다고 생각하기 때문에 이유가 궁금합니다. 예 : http://stackoverflow.com/questions/5134786/cached-property-vs-lazyt?rq=1 –
첫 번째 것은 대부분 'Bootstrap = InitializeContainer();'를 작성하는 것과 동일합니다. 포함하는 클래스의 정적 생성자가 실행될 때만 초기화를 컨테이너에 액세스하는 시간에 위임하지 않습니다. 이 경우에는'게으른'을 사용하는 것이 거의 없습니다. – Luaan