Skip to content

Instantly share code, notes, and snippets.

@mgroves
Created March 3, 2013 22:10
Show Gist options
  • Select an option

  • Save mgroves/5078543 to your computer and use it in GitHub Desktop.

Select an option

Save mgroves/5078543 to your computer and use it in GitHub Desktop.
PostSharp lazy loading aspect that uses Lazy<T>
[Serializable]
public class LazyLoadStructureMap : LocationInterceptionAspect
{
Lazy<object> _backingField;
public override void OnGetValue(LocationInterceptionArgs args)
{
if (_backingField == null)
_backingField = new Lazy<object>(() =>
{
var locationType = args.Location.PropertyInfo.PropertyType;
return ObjectFactory.GetInstance(locationType);
});
args.Value = _backingField.Value;
}
}
@mgroves
Copy link
Copy Markdown
Author

mgroves commented Mar 3, 2013

I'm trying to leverage Lazy<T> to do all the dirty work with locking and so forth, but it seems like there could still be a race condition around lines 8 & 9.

@gfraiteur
Copy link
Copy Markdown

I think you should not use Lazy here, but just a bool field to remember if the field has been retrieved yet or not. There could be a race (probably harmless), you could get rid of it by using a lock and double lookup. Also, you need the aspect to implement IInstanceScopedAspect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment