using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using msdi = Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Collections.Generic;
namespace Falcon.DI
{
///
/// 服务集合方法扩展
///
public static class IServiceCollectionExtend
{
///
/// 实现自动DI注册
///
/// 服务集合
/// 要注册的程序集集合,如果未指定则为CurrentDomain所有引入的程序集
public static IServiceCollection UseFalconDI(this IServiceCollection services,params Assembly[] assemblies) {
if(assemblies == null || assemblies.Length == 0) {
return services.UseFalconDI(AppDomain.CurrentDomain.GetAssemblies());
}
foreach(Assembly ass in assemblies) {
foreach(Type type in ass.GetTypes()) {
if(!type.CanInstance()) {
continue;
}
var ra = type.GetCustomAttribute(true);
if(ra != null) {
//如果未提供服务类型,注册到所有实现的接口和基类
if(ra.ServiceTypes == null || ra.ServiceTypes.Length == 0) {
var sts = new List();
//添加所有实现的接口
sts.AddRange(type.GetInterfaces());
//添加非object基类
var baseType = type.BaseType;
if(baseType != typeof(object)) {
sts.Add(baseType);
}
//添加类型本身
sts.Add(type);
ra.ServiceTypes = sts.ToArray();
}
foreach(var ser in ra.ServiceTypes) {
services.Add(new ServiceDescriptor(ser,type,convertLifetime(ra.Lifetime)));
}
}
}
}
return services;
}
///
/// 转换生存期枚举
///
/// 生存期
///
private static msdi.ServiceLifetime convertLifetime(ServiceLifetime lt) {
return (msdi.ServiceLifetime)(int)lt;
}
///
/// 获取类型是否可以实例化。
///
/// 类型
/// 是否可实例化
public static bool CanInstance(this Type type) {
if(!type.IsClass || type.IsAbstract) {
return false;
}
return true;
}
}
}