Skip to content

Commit

Permalink
Add keyed service support
Browse files Browse the repository at this point in the history
  • Loading branch information
gehongyan committed Nov 6, 2024
1 parent 75355f7 commit d81d27e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
4 changes: 4 additions & 0 deletions src/Kook.Net.Commands/Kook.Net.Commands.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,8 @@
<ProjectReference Include="..\Kook.Net.Core\Kook.Net.Core.csproj"/>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.2" />
</ItemGroup>

</Project>
11 changes: 7 additions & 4 deletions src/Kook.Net.Commands/Utilities/ReflectionUtils.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;

namespace Kook.Commands;

Expand All @@ -18,12 +19,12 @@ internal static Func<IServiceProvider, T> CreateBuilder<T>(TypeInfo typeInfo, Co
return services =>
{
object[] args = parameters
.Select(x => GetMember(commands, services, x.ParameterType, typeInfo))
.Select(x => GetMember(commands, services, x.ParameterType, typeInfo, x.GetCustomAttributes()))
.ToArray();
T obj = InvokeConstructor<T>(constructor, args, typeInfo);
foreach (PropertyInfo property in properties)
property.SetValue(obj, GetMember(commands, services, property.PropertyType, typeInfo));
property.SetValue(obj, GetMember(commands, services, property.PropertyType, typeInfo, null));
return obj;
};
}
Expand Down Expand Up @@ -68,11 +69,13 @@ private static PropertyInfo[] GetProperties(TypeInfo? ownerType)
return result.ToArray();
}

private static object GetMember(CommandService commands, IServiceProvider services, Type memberType, TypeInfo ownerType)
private static object GetMember(CommandService commands, IServiceProvider services, Type memberType, TypeInfo ownerType, IEnumerable<object>? attributes)
{
if (memberType == typeof(CommandService)) return commands;
if (memberType == typeof(IServiceProvider) || memberType == services.GetType()) return services;
object? service = services.GetService(memberType);
object? service = attributes?.FirstOrDefault(x => x.GetType() == typeof(FromKeyedServicesAttribute)) is { } keyedAttribute
? services.GetKeyedServices(memberType, ((FromKeyedServicesAttribute)keyedAttribute).Key).First()
: services.GetService(memberType);
if (service != null) return service;
throw new InvalidOperationException($"Failed to create \"{ownerType.FullName}\", dependency \"{memberType.Name}\" was not found.");
}
Expand Down

0 comments on commit d81d27e

Please sign in to comment.