加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
AttributeSelector.cs 2.53 KB
一键复制 编辑 原始数据 按行查看 历史
nodyang 提交于 2022-01-08 20:06 . 添加项目文件。
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;
}
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化