Falcon.Di/Falcon.DI/IServiceCollectionExtend.cs
2019-12-27 11:39:10 +08:00

76 lines
3.0 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using msdi = Microsoft.Extensions.DependencyInjection;
using System.Linq;
using System.Collections.Generic;
namespace Falcon.DI
{
/// <summary>
/// 服务集合方法扩展
/// </summary>
public static class IServiceCollectionExtend
{
/// <summary>
/// 实现自动DI注册
/// </summary>
/// <param name="services">服务集合</param>
/// <param name="assemblies">要注册的程序集集合如果未指定则为CurrentDomain所有引入的程序集</param>
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<FalconDIRegisterAttribute>(true);
if(ra != null) {
//如果未提供服务类型,注册到所有实现的接口和基类
if(ra.ServiceTypes == null || ra.ServiceTypes.Length == 0) {
var sts = new List<Type>();
//添加所有实现的接口
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;
}
/// <summary>
/// 转换生存期枚举
/// </summary>
/// <param name="lt">生存期</param>
/// <returns></returns>
private static msdi.ServiceLifetime convertLifetime(ServiceLifetime lt) {
return (msdi.ServiceLifetime)(int)lt;
}
/// <summary>
/// 获取类型是否可以实例化。
/// </summary>
/// <param name="type">类型</param>
/// <returns>是否可实例化</returns>
public static bool CanInstance(this Type type) {
if(!type.IsClass || type.IsAbstract) {
return false;
}
return true;
}
}
}