MonodroidStockPortfolio/MonoStockPortfolio/Framework/IoCAttribute.cs

42 lines
1.6 KiB
C#
Raw Normal View History

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
{
args.ProceedGetValue();
if (args.Value == null) // lazy loading
{
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");
ResolveContextDependency((Context)args.Instance);
var dependencyType = args.Location.LocationType;
var instantiation = ServiceLocator.Get(dependencyType);
if (instantiation != null)
{
args.SetNewValue(instantiation);
}
args.ProceedGetValue();
2010-12-19 20:34:20 +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
}
}