C# 自动依赖注入(反射)

自定义注解 [Injectable],自动依赖注入
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Demo
{
    /// <summary>
    /// 自定义注解 [Injectable],自动依赖注入
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class InjectableAttribute : Attribute
    {
        /// <summary>
        /// 服务的生命周期
        /// </summary>
        public ServiceLifetime Lifetime { get; }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="lifetime">服务的生命周期</param>
        public InjectableAttribute(ServiceLifetime lifetime = ServiceLifetime.Transient)
        {
            Lifetime = lifetime;
        }
    }
}
View Code

依赖注入容器

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace Demo
{
    /// <summary>
    /// 依赖注入容器
    /// </summary>
    public static class DIContainer
    {
        /// <summary>
        /// 服务提供者
        /// </summary>
        private static IServiceProvider _serviceProvider;
        /// <summary>
        /// 自动注入依赖
        /// </summary>
        public static void AutoInjectDependencies(this IServiceCollection serviceCollection)
        {
            ConfigureServices(serviceCollection);
            _serviceProvider = serviceCollection.BuildServiceProvider();
        }
        /// <summary>
        /// 注册服务到容器
        /// </summary>
        /// <param name="services"></param>
        private static void ConfigureServices(IServiceCollection services)
        {
            // 获取指定程序集的类
            List<Type> types = new List<Type>();
            types.AddRange(Assembly.GetExecutingAssembly().GetTypes());
            types.AddRange(Assembly.Load("RCS").GetTypes());
            // 遍历类
            foreach (var type in types)
            {
                // 判断类的注解
                var injectableAttribute = type.GetCustomAttribute<InjectableAttribute>();
                if (injectableAttribute != null)
                {
                    var lifetime = injectableAttribute?.Lifetime ?? ServiceLifetime.Transient;
                    // 注册类
                    switch (lifetime)
                    {
                        case ServiceLifetime.Singleton:
                            services.AddSingleton(type);
                            break;
                        case ServiceLifetime.Scoped:
                            services.AddScoped(type);
                            break;
                        case ServiceLifetime.Transient:
                            services.AddTransient(type);
                            break;
                        default:
                            services.AddTransient(type);
                            break;
                    }
                    // 判断是否泛型
                    if (!type.IsGenericType)
                    {
                        // 判断类是否继承接口
                        var interfaceType = type.GetInterfaces().FirstOrDefault();
                        if (interfaceType != null)
                        {
                            // 注册接口
                            services.AddSingleton(interfaceType, type);
                            switch (lifetime)
                            {
                                case ServiceLifetime.Singleton:
                                    services.AddSingleton(interfaceType, type);
                                    break;
                                case ServiceLifetime.Scoped:
                                    services.AddScoped(interfaceType, type);
                                    break;
                                case ServiceLifetime.Transient:
                                    services.AddTransient(interfaceType, type);
                                    break;
                                default:
                                    services.AddTransient(interfaceType, type);
                                    break;
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 获取服务实例
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetService<T>()
        {
            return _serviceProvider.GetRequiredService<T>();
        }
        /// <summary>
        /// 获取服务实例
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object GetService(Type type)
        {
            return _serviceProvider.GetRequiredService(type);
        }
    }
}
View Code

使用方法:

需要注入的类/接口类

[Injectable(ServiceLifetime.Singleton)]
public class Class1
{}
[Injectable(ServiceLifetime.Singleton)]
public class Class1 :IService
{}

Startup.cs

// 自动注入依赖
services.AutoInjectDependencies();

 

posted @ 2024-04-02 10:48  Mr_Xul  阅读(110)  评论(0编辑  收藏  举报