Created
March 3, 2013 22:10
-
-
Save mgroves/5078543 to your computer and use it in GitHub Desktop.
PostSharp lazy loading aspect that uses Lazy<T>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [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; | |
| } | |
| } |
Author
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
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.