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.
This commit is contained in:
Christopher F
2016-12-14 16:38:28 -05:00
parent 0f334d24a0
commit b33df6ad77
2 changed files with 26 additions and 1 deletions

View File

@@ -0,0 +1,9 @@
using System;
namespace Discord.Commands
{
[AttributeUsage(AttributeTargets.Field)]
public class InjectAttribute : Attribute
{
}
}

View File

@@ -42,7 +42,23 @@ namespace Discord.Commands
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)
{