Skip to content

Instantly share code, notes, and snippets.

@toeb
Created May 8, 2018 23:45
Show Gist options
  • Save toeb/67b1be206b269a9b883934d6cbc7cb35 to your computer and use it in GitHub Desktop.
Save toeb/67b1be206b269a9b883934d6cbc7cb35 to your computer and use it in GitHub Desktop.
/// <summary> A DependencyObject extension method that gets injection service by enumerating the visual tree. </summary>
///
/// <remarks> Toeb, 2018-04-23. </remarks>
///
/// <param name="TargetObject"> . </param>
///
/// <returns> The injection service. </returns>
public static IInjectionService GetInjectionService(this DependencyObject TargetObject)
{
// needs to be extended to look at the views themselves
foreach (var obj in TargetObject.EnumerateParentViewModels())
{
if (obj is IInjector ij)
{
return ij.Injector;
}
}
return null;
}
/// <summary> Resolves the content for a specified dependency object. </summary>
///
/// <remarks> Toeb, 2018-04-23. </remarks>
///
/// <param name="TargetObject"> . </param>
/// <param name="content"> . </param>
/// <param name="parameters"> (Optional) </param>
///
/// <returns> An object. </returns>
public static object ResolveContent(this DependencyObject TargetObject, object content, object[] parameters = null)
{
var injectionService = TargetObject.GetInjectionService() ?? Application.Current.RootInjector();
var reflectionService = injectionService?.GetService<IReflectionService>();
if (content is string str)
{
if (Regex.IsMatch(str, "^[a-zA-Z_][a-zA-Z_0-9]*$"))
{
// identifier
if (injectionService != null)
{
var types = reflectionService.FindTypeByPartialName(str).ToArray();
var t = types.SingleOrDefault();
if(t!=null)
{
return injectionService.Construct(t, parameters);
}
}
}
try
{
var componentUri = new Uri(BaseUriHelper.GetBaseUri(TargetObject), "..");
if (Uri.TryCreate(str, UriKind.RelativeOrAbsolute, out var newUri))
{
componentUri = newUri;
}
else
{
componentUri = new Uri(componentUri, str);
}
var item = Application.LoadComponent(componentUri);
return item;
}
catch (Exception e)
{
Trace.TraceInformation($"failed to load uri content {str}");
return null;
}
}
if (content is Type type)
{
if (injectionService == null)
{
return null;
}
return injectionService.Construct(type, parameters);
}
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment