tnblog
首页
视频
资源
登录

程序集依赖注入笔记

3829人阅读 2020/7/30 14:04 总访问:76534 评论:0 收藏:0 手机
分类: .netcore

 public static class IServiceCollectionExtension

    {

        /// <summary>

        /// 程序集依赖注入

        /// </summary>

        /// <param name="services"></param>

        /// <param name="assemblyName"></param>

        /// <param name="serviceLifetime"></param>

        public static void GetAssembly(this IServiceCollection services, string assemblyName, ServiceLifetime serviceLifetime = ServiceLifetime.Singleton)

        {

            if (!String.IsNullOrEmpty(assemblyName))

            {

                Assembly assembly = Assembly.Load(assemblyName);

                List<Type> ts = assembly.GetTypes().ToList();

                var result = new Dictionary<Type, Type[]>();

                if (ts != null)

                {

                    var tsAssemblyList = ts.Where(o => o.IsClass && !o.IsAbstract && !o.IsGenericType && o.Name.Contains("Service"));

                    foreach (var item in tsAssemblyList)

                    {

                        var interfaceType = item.GetInterfaces().First();

                        switch (serviceLifetime)

                        {

                            case ServiceLifetime.Scoped:

                                services.AddScoped(interfaceType, item);

                                break;

                            case ServiceLifetime.Singleton:

                                services.AddSingleton(interfaceType, item);

                                break;

                            case ServiceLifetime.Transient:

                                services.AddTransient(interfaceType, item);

                                break;

                        }

                    }

                }

            }

        }

    }


评价
此时幽梦远,不觉到山边!!!
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术