• 自己实现的一个简单的C# IOC 容器


    IService接口,以实现服务的启动、停止功能:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Utils
    {
        /// <summary>
        /// 服务接口
        /// </summary>
        public interface IService
        {
            /// <summary>
            /// 服务启动
            /// </summary>
            void OnStart();
    
            /// <summary>
            /// 服务停止
            /// </summary>
            void OnStop();
        }
    }
    View Code

    AbstractService服务抽象类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Utils
    {
        /// <summary>
        /// 服务抽象类
        /// </summary>
        public abstract class AbstractService : IService
        {
            /// <summary>
            /// 服务启动
            /// </summary>
            public virtual void OnStart() { }
    
            /// <summary>
            /// 服务停止
            /// </summary>
            public virtual void OnStop() { }
        }
    }
    View Code

    IOC容器帮助类:

    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Threading.Tasks;
    using System.Web;
    
    namespace Utils
    {
        /// <summary>
        /// 服务帮助类
        /// </summary>
        public partial class ServiceHelper
        {
            #region 变量
            /// <summary>
            /// 接口的对象集合
            /// </summary>
            private static ConcurrentDictionary<Type, object> _dict = new ConcurrentDictionary<Type, object>();
            #endregion
    
            #region Get 获取实例
            /// <summary>
            /// 获取实例
            /// </summary>
            public static T Get<T>()
            {
                Type type = typeof(T);
                object obj = _dict.GetOrAdd(type, key => Activator.CreateInstance(type));
    
                return (T)obj;
            }
            #endregion
    
            #region Get 通过Func获取实例
            /// <summary>
            /// 获取实例
            /// </summary>
            public static T Get<T>(Func<T> func)
            {
                Type type = typeof(T);
                object obj = _dict.GetOrAdd(type, (key) => func());
    
                return (T)obj;
            }
            #endregion
    
            #region RegisterAssembly 注册程序集
            /// <summary>
            /// 注册程序集
            /// </summary>
            /// <param name="type">程序集中的一个类型</param>
            public static void RegisterAssembly(Type type)
            {
                RegisterAssembly(Assembly.GetAssembly(type).FullName);
            }
    
            /// <summary>
            /// 注册程序集
            /// </summary>
            /// <param name="assemblyString">程序集名称的长格式</param>
            public static void RegisterAssembly(string assemblyString)
            {
                LogTimeUtil logTimeUtil = new LogTimeUtil();
                Assembly assembly = Assembly.Load(assemblyString);
                Type[] typeArr = assembly.GetTypes();
                string iServiceInterfaceName = typeof(IService).FullName;
    
                foreach (Type type in typeArr)
                {
                    Type typeIService = type.GetInterface(iServiceInterfaceName);
                    if (typeIService != null && !type.IsAbstract)
                    {
                        Type[] interfaceTypeArr = type.GetInterfaces();
                        object obj = Activator.CreateInstance(type);
                        _dict.GetOrAdd(type, obj);
    
                        foreach (Type interfaceType in interfaceTypeArr)
                        {
                            if (interfaceType != typeof(IService))
                            {
                                _dict.GetOrAdd(interfaceType, obj);
                            }
                        }
                    }
                }
                logTimeUtil.LogTime("ServiceHelper.RegisterAssembly 注册程序集 " + assemblyString + " 耗时");
            }
            #endregion
    
            #region 启动所有服务
            /// <summary>
            /// 启动所有服务
            /// </summary>
            public static Task StartAllService()
            {
                return Task.Run(() =>
                {
                    List<Task> taskList = new List<Task>();
                    foreach (object o in _dict.Values.Distinct())
                    {
                        Task task = Task.Factory.StartNew(obj =>
                        {
                            IService service = obj as IService;
    
                            try
                            {
                                service.OnStart();
                                LogUtil.Log("服务 " + obj.GetType().FullName + " 已启动");
                            }
                            catch (Exception ex)
                            {
                                LogUtil.Error(ex, "服务 " + obj.GetType().FullName + " 启动失败");
                            }
                        }, o);
                        taskList.Add(task);
                    }
                    Task.WaitAll(taskList.ToArray());
                });
            }
            #endregion
    
            #region 停止所有服务
            /// <summary>
            /// 停止所有服务
            /// </summary>
            public static Task StopAllService()
            {
                return Task.Run(() =>
                {
                    List<Task> taskList = new List<Task>();
                    Type iServiceInterfaceType = typeof(IService);
                    foreach (object o in _dict.Values.Distinct())
                    {
                        Task task = Task.Factory.StartNew(obj =>
                        {
                            if (iServiceInterfaceType.IsAssignableFrom(obj.GetType()))
                            {
                                IService service = obj as IService;
    
                                try
                                {
                                    service.OnStop();
                                    LogUtil.Log("服务 " + obj.GetType().FullName + " 已停止").Wait();
                                }
                                catch (Exception ex)
                                {
                                    LogUtil.Error(ex, "服务 " + obj.GetType().FullName + " 停止失败").Wait();
                                }
                            }
                        }, o);
                        taskList.Add(task);
                    }
                    Task.WaitAll(taskList.ToArray());
                });
            }
            #endregion
    
        }
    }
    View Code

    说明:

    RegisterAssembly方法:注册实现类,只要程序集中的类实现了某个接口,就注册,把它的类型以及接口的类型作为Key添加到字典中,以接口类型作为Key的时候,过滤掉IService这个接口。

    StartAllService方法:调用所有服务的OnStart方法。

    StopAllService方法:调用所有服务的OnStop方法。

    如何使用:

    服务的注册与启动:

    ServiceHelper.RegisterAssembly(typeof(MyActionFilter));
    ServiceHelper.StartAllService().Wait();
    View Code

    说明:RegisterAssembly方法的参数,传递程序集中任何一个类型即可。

    服务的停止:

    ServiceHelper.StopAllService().Wait();
    View Code

    服务的定义:

    using Models;
    using Newtonsoft.Json;
    using NetWebApi.DAL;
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Reflection;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Timers;
    using System.Web;
    using System.Collections.Concurrent;
    using Utils;
    using System.Configuration;
    
    namespace NetWebApi.BLL
    {
        /// <summary>
        /// 通用
        /// </summary>
        public class CommonBll : AbstractService
        {
            #region OnStart 服务启动
            /// <summary>
            /// 服务启动
            /// </summary>
            public override void OnStart()
            {
    
            }
            #endregion
    
            #region OnStop 服务停止
            /// <summary>
            /// 服务停止
            /// </summary>
            public override void OnStop()
            {
    
            }
            #endregion
    
        }
    }
    View Code

    调用服务:

    CommonBll commonBll = ServiceHelper.Get<CommonBll>();
    View Code

    临时注册并调用服务:

    SaveDataBll m_SaveDataBll = ServiceHelper.Get<SaveDataBll>();
    View Code
  • 相关阅读:
    隆重推出PowerDesinger 12.1.0.1913破解补丁
    Glowcode 6.0 破解手记,.Net IL技术
    爬虫如何抓取到Asp.Net中__doPostBack获取新页面的数据
    谁是股市上的最大受益者
    带强名的.net程序反向工程后汇编中的问题总结
    让所有的实体店成为网店的体验店
    推出网站大鱼搜索
    利用搜索引擎技术抢注域名
    在程序中显示PDF文件不依赖于Arcobat Reader的PDF阅读器开发
    用开源Carrot2的后缀树算法做Web文本聚类
  • 原文地址:https://www.cnblogs.com/s0611163/p/15166869.html
Copyright © 2020-2023  润新知