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:
9
src/Discord.Net.Commands/Attributes/InjectAttribute.cs
Normal file
9
src/Discord.Net.Commands/Attributes/InjectAttribute.cs
Normal file
@@ -0,0 +1,9 @@
|
||||
using System;
|
||||
|
||||
namespace Discord.Commands
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Field)]
|
||||
public class InjectAttribute : Attribute
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user