五维思考

学习要加,骄傲要减,机会要乘,懒惰要除。 http://www.5dthink.cn

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

前言:

在Autofac的使用中,提供了个种注入的API其中GetAssemblies()用着特别的舒坦。

1、core2.0也可以使用Autofac的包,但框架自身也提供了默认的注入Api,IServiceCollection(Transient、AddSingleton、Scoped)

services.AddTransient<IUserRepositiry, UserRepositiry>();
services.AddSingleton<IUserRepositiry, UserRepositiry>();
services.AddScoped<IUserRepositiry, UserRepositiry>();

上面是框架自带的注入(如果有100个类,那岂不是要写100遍,脑壳痛。。。)

2、按程序集实现依赖注入

using General.Core.Librs;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;

namespace General.Core.Extensions
{
    /// <summary>
    /// IServiceCollection 容器的拓展类
    /// </summary>
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 程序集依赖注入
        /// </summary>
        /// <param name="services"></param>
        /// <param name="assemblyName"></param>
        /// <param name="serviceLifetime"></param>
        public static void AddAssembly(this IServiceCollection services, string assemblyName, ServiceLifetime serviceLifetime = ServiceLifetime.Scoped)
        {
            if (services == null)
                throw new ArgumentNullException(nameof(services) + "为空");

            if (String.IsNullOrEmpty(assemblyName))
                throw new ArgumentNullException(nameof(assemblyName) + "为空");

            var assembly = RuntimeHelper.GetAssemblyByName(assemblyName);

            if (assembly == null)
                throw new DllNotFoundException(nameof(assembly) + ".dll不存在");

            var types = assembly.GetTypes();
            var list = types.Where(o => o.IsClass && !o.IsAbstract && !o.IsGenericType).ToList();
            if (list == null && !list.Any())
                return;
            foreach (var type in list)
            {
                var interfacesList = type.GetInterfaces();
                if (interfacesList == null || !interfacesList.Any())
                    continue;
                var inter = interfacesList.First();
                switch (serviceLifetime)
                {
                    case ServiceLifetime.Scoped:
                        services.AddScoped(inter, type);
                        break;
                    case ServiceLifetime.Singleton:
                        services.AddScoped(inter, type);
                        break;
                    case ServiceLifetime.Transient:
                        services.AddTransient(inter, type);
                        break;
                }
            }
        }
    }
}

 

在Startup.cs的 ConfigureServices(IServiceCollection services)方法中调用

services.RegisterAssembly("General.Services");

这样就实现了!

posted on 2020-01-19 11:04  五维思考  阅读(745)  评论(0编辑  收藏  举报

QQ群:1. 全栈码农【346906288】2. VBA/VSTO【2660245】