前言:

在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");

这样就实现了!

相关文章:

  • 2021-09-17
  • 2021-06-19
  • 2022-02-15
  • 2022-12-23
  • 2022-02-28
  • 2021-11-12
  • 2021-11-20
猜你喜欢
  • 2021-05-18
  • 2021-06-14
  • 2022-02-17
  • 2021-09-13
  • 2021-07-28
  • 2022-01-27
相关资源
相似解决方案