Browse Source

Add InjectAttribute, inject into fields flagged with it from DepMap

This allows users to flag a field with InjectAttribute, and when the module is created at runtime, this field will be filled in with the object from the dependency map.
tags/1.0-rc
Christopher F 8 years ago
parent
commit
b33df6ad77
2 changed files with 26 additions and 1 deletions
  1. +9
    -0
      src/Discord.Net.Commands/Attributes/InjectAttribute.cs
  2. +17
    -1
      src/Discord.Net.Commands/Utilities/ReflectionUtils.cs

+ 9
- 0
src/Discord.Net.Commands/Attributes/InjectAttribute.cs View File

@@ -0,0 +1,9 @@
using System;

namespace Discord.Commands
{
[AttributeUsage(AttributeTargets.Field)]
public class InjectAttribute : Attribute
{
}
}

+ 17
- 1
src/Discord.Net.Commands/Utilities/ReflectionUtils.cs View File

@@ -42,7 +42,23 @@ namespace Discord.Commands


try try
{ {
return (T)constructor.Invoke(args);
T type = (T)constructor.Invoke(args);
var fields = type.GetType().GetRuntimeFields().Where(p => p.GetCustomAttribute<InjectAttribute>() != null);
foreach (var field in fields)
{
object arg;
if (map == null || !map.TryGet(field.FieldType, out arg))
{
if (field.FieldType == typeof(CommandService))
arg = service;
else if (field.FieldType == typeof(IDependencyMap))
arg = map;
else
throw new InvalidOperationException($"Failed to inject \"{typeInfo.FullName}\", dependency \"{field.FieldType.FullName}\" was not found.");
}
field.SetValue(type, arg);
}
return type;
} }
catch (Exception ex) catch (Exception ex)
{ {


Loading…
Cancel
Save