Merge pull request #520 from james7132/property-injection

Conflicts:
	docs/guides/samples/dependency_module.cs
	src/Discord.Net.Commands/Utilities/ReflectionUtils.cs
This commit is contained in:
Christopher F
2017-02-23 15:51:24 -05:00
4 changed files with 157 additions and 114 deletions

View File

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

View File

@@ -19,6 +19,9 @@ namespace Discord.Commands
var constructor = constructors[0];
System.Reflection.ParameterInfo[] parameters = constructor.GetParameters();
System.Reflection.PropertyInfo[] properties = typeInfo.DeclaredProperties
.Where(p => p.SetMethod?.IsPublic == true && p.GetCustomAttribute<DontInjectAttribute>() == null)
.ToArray();
return (map) =>
{
@@ -27,29 +30,40 @@ namespace Discord.Commands
for (int i = 0; i < parameters.Length; i++)
{
var parameter = parameters[i];
object arg;
if (map == null || !map.TryGet(parameter.ParameterType, out arg))
{
if (parameter.ParameterType == typeof(CommandService))
arg = service;
else if (parameter.ParameterType == typeof(IDependencyMap))
arg = map;
else
throw new InvalidOperationException($"Failed to create \"{typeInfo.FullName}\", dependency \"{parameter.ParameterType.Name}\" was not found.");
}
args[i] = arg;
args[i] = GetMember(parameter.ParameterType, map, service, typeInfo);
}
T obj;
try
{
T instance = (T)constructor.Invoke(args);
return instance;
obj = (T)constructor.Invoke(args);
}
catch (Exception ex)
{
throw new Exception($"Failed to create \"{typeInfo.FullName}\"", ex);
}
foreach(var property in properties)
{
property.SetValue(obj, GetMember(property.PropertyType, map, service, typeInfo));
}
return obj;
};
}
internal static object GetMember(Type targetType, IDependencyMap map, CommandService service, TypeInfo baseType)
{
object arg;
if (map == null || !map.TryGet(targetType, out arg))
{
if (targetType == typeof(CommandService))
arg = service;
else if (targetType == typeof(IDependencyMap))
arg = map;
else
throw new InvalidOperationException($"Failed to create \"{baseType.FullName}\", dependency \"{targetType.Name}\" was not found.");
}
return arg;
}
}
}