自己實現的一個簡單的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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM