2011-03-06 18:46:04 +00:00
|
|
|
using System;
|
2010-12-19 20:34:20 +00:00
|
|
|
using Android.Content;
|
|
|
|
using PostSharp.Aspects;
|
|
|
|
|
2010-12-27 04:18:10 +00:00
|
|
|
namespace MonoStockPortfolio.Framework
|
2010-12-19 20:34:20 +00:00
|
|
|
{
|
|
|
|
public class IoCAttribute : LocationInterceptionAspect
|
|
|
|
{
|
2011-02-06 01:48:55 +00:00
|
|
|
public sealed override void OnGetValue(LocationInterceptionArgs args)
|
2010-12-19 20:34:20 +00:00
|
|
|
{
|
2011-03-06 18:46:04 +00:00
|
|
|
args.ProceedGetValue();
|
|
|
|
if (args.Value == null) // lazy loading
|
2010-12-27 02:47:10 +00:00
|
|
|
{
|
2011-03-06 18:46:04 +00:00
|
|
|
var context = args.Instance as Context;
|
|
|
|
if(context == null) throw new Exception("The IoC Aspect can only be used on a field within an Activity (or Context) object");
|
2011-01-02 22:10:27 +00:00
|
|
|
|
2011-03-06 18:46:04 +00:00
|
|
|
ResolveContextDependency((Context)args.Instance);
|
|
|
|
|
|
|
|
var dependencyType = args.Location.LocationType;
|
|
|
|
var instantiation = ServiceLocator.Get(dependencyType);
|
2011-01-02 22:10:27 +00:00
|
|
|
|
2011-03-06 15:21:31 +00:00
|
|
|
if (instantiation != null)
|
|
|
|
{
|
|
|
|
args.SetNewValue(instantiation);
|
|
|
|
}
|
|
|
|
args.ProceedGetValue();
|
2010-12-19 20:34:20 +00:00
|
|
|
}
|
|
|
|
}
|
2011-03-06 18:46:04 +00:00
|
|
|
|
|
|
|
private static void ResolveContextDependency(Context contextObject)
|
|
|
|
{
|
|
|
|
if (ServiceLocator.Context == null)
|
|
|
|
{
|
|
|
|
// note the double ApplicationContext
|
|
|
|
// is because the context's reference could get garbage collected while the app is still goin
|
|
|
|
// for whatever reason, but it's reference's reference is long-running
|
|
|
|
// and since this context dependency is mainly used for Sqlite, that's the most ideal one
|
|
|
|
ServiceLocator.Context = contextObject.ApplicationContext.ApplicationContext;
|
|
|
|
}
|
|
|
|
}
|
2010-12-19 20:34:20 +00:00
|
|
|
}
|
|
|
|
}
|