代码拉取完成,页面将自动刷新
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Chims.Extensions.DI
{
internal class AttributeSelector : ISelector
{
public AttributeSelector(IEnumerable<Type> types)
{
Types = types;
}
private IEnumerable<Type> Types { get; }
void ISelector.Populate(IServiceCollection services)
{
if (services == null) throw new ArgumentNullException(nameof(services));
foreach (var type in Types)
{
var typeInfo = type.GetTypeInfo();
var attributes = typeInfo.GetCustomAttributes<ServiceDescriptorAttribute>().ToArray();
// Check if the type has multiple attributes with same ServiceType.
var duplicates = attributes
.GroupBy(s => s.ServiceType)
.SelectMany(grp => grp.Skip(1));
if (duplicates.Any())
throw new InvalidOperationException(
$@"Type ""{type.FullName}"" has multiple ServiceDescriptor attributes with the same service type.");
foreach (var attribute in attributes)
{
var serviceTypes = GetServiceTypes(type, attribute);
foreach (var serviceType in serviceTypes)
{
var descriptor = new ServiceDescriptor(serviceType, type, attribute.Lifetime);
services.Add(descriptor);
}
}
}
}
private static IEnumerable<Type> GetServiceTypes(Type type, ServiceDescriptorAttribute attribute)
{
var typeInfo = type.GetTypeInfo();
var serviceType = attribute.ServiceType;
if (serviceType == null)
{
yield return type;
foreach (var implementedInterface in typeInfo.ImplementedInterfaces) yield return implementedInterface;
if (typeInfo.BaseType != null && typeInfo.BaseType != typeof(object)) yield return typeInfo.BaseType;
yield break;
}
var serviceTypeInfo = serviceType.GetTypeInfo();
if (!serviceTypeInfo.IsAssignableFrom(typeInfo))
throw new InvalidOperationException(
$@"Type ""{typeInfo.FullName}"" is not assignable to ""${serviceTypeInfo.FullName}"".");
yield return serviceType;
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。