ASP.NET Core 3.0 原生DI拓展实现IocManager

昨天.NET Core 3.0正式发布,创建一个项目运行后发现:原来使用的Autofac在ConfigureServices返回IServiceProvider的这种写法已经不再支持。

当然Autofac官方也给出了示例。.NET Core 本身内置DI,我决定不再使用Autofac,就使用原生DI,拓展IServiceCollection实现一个IocManager,

实现批量注入,静态获取实例能。末尾处含有Autofac IocManager实现方式。

一、Autofac官方文档

Program Class

Hosting changed in ASP.NET Core 3.0 and requires a slightly different integration. This is for ASP.NET Core 3+ and the .NET Core 3+ generic hosting support:

public class Program
{
  public static void Main(string[] args)
  {
    // ASP.NET Core 3.0+:
    // The UseServiceProviderFactory call attaches the
    // Autofac provider to the generic hosting mechanism.
    var host = Host.CreateDefaultBuilder(args)
        .UseServiceProviderFactory(new AutofacServiceProviderFactory())
        .ConfigureWebHostDefaults(webHostBuilder => {
          webHostBuilder
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup();
        })
        .Build();

    host.Run();
  }
}

Startup Class

In your Startup class (which is basically the same across all the versions of ASP.NET Core) you then use ConfigureContainer to access the Autofac container builder and register things directly with Autofac.

public class Startup
{
  public Startup(IHostingEnvironment env)
  {
    // In ASP.NET Core 3.0 env will be an IWebHostingEnvironment, not IHostingEnvironment.
    var builder = new ConfigurationBuilder()
        .SetBasePath(env.ContentRootPath)
        .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
        .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
        .AddEnvironmentVariables();
    this.Configuration = builder.Build();
  }

  public IConfigurationRoot Configuration { get; private set; }

  public ILifetimeScope AutofacContainer { get; private set; }

  // ConfigureServices is where you register dependencies. This gets
  // called by the runtime before the ConfigureContainer method, below.
  public void ConfigureServices(IServiceCollection services)
  {
    // Add services to the collection. Don't build or return
    // any IServiceProvider or the ConfigureContainer method
    // won't get called.
    services.AddOptions();
  }

  // ConfigureContainer is where you can register things directly
  // with Autofac. This runs after ConfigureServices so the things
  // here will override registrations made in ConfigureServices.
  // Don't build the container; that gets done for you. If you
  // need a reference to the container, you need to use the
  // "Without ConfigureContainer" mechanism shown later.
  public void ConfigureContainer(ContainerBuilder builder)
  {
      builder.RegisterModule(new AutofacModule());
  }

  // Configure is where you add middleware. This is called after
  // ConfigureContainer. You can use IApplicationBuilder.ApplicationServices
  // here if you need to resolve things from the container.
  public void Configure(
    IApplicationBuilder app,
    ILoggerFactory loggerFactory)
  {
    // If, for some reason, you need a reference to the built container, you
    // can use the convenience extension method GetAutofacRoot.
    this.AutofacContainer = app.ApplicationServices.GetAutofacRoot();

    loggerFactory.AddConsole(this.Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();
    app.UseMvc();
  }
}

二、IocManager实现

1、创建IocManager

IIocManager接口

public interface IIocManager
{
    IServiceProvider ServiceProvider { get; set; }
}

IocManager实现

public class IocManager : IIocManager
{
    static IocManager()
    {
        Instance = new IocManager();
    }
    public static IocManager Instance { get; private set; }
    public IServiceProvider ServiceProvider { get; set; }
}

2、创建生命周期接口

    /// 
    ///    标记依赖项生命周期的接口
    ///     ,
    ///     ,
    ///     
    /// 
    public interface ILifetime { }
    /// 
    /// 确定接口或类的生存期
    /// 单例模式,所有服务请求都将会返回同一个实例。
    /// 
    public interface ISingletonDependency: ILifetime { }
    /// 
    /// 确定接口或类的生存期
    /// 作用域模式,服务在每次请求时被创建,整个请求过程中都贯穿使用这个创建的服务。
    /// 
    public interface ILifetimeScopeDependency : ILifetime { }
    /// 
    /// 确定接口或类的生存期
    /// 瞬态模式,每次请求时都会创建。
    /// 
    public interface ITransientDependency : ILifetime { }

3、拓展IServiceCollection

/// 
/// .NET Core 依赖注入拓展
/// 
public static class DependencyInjectionExtensions
{
    /// 
    /// 注册程序集组件
    /// 
    /// 
    /// 
    /// 
    public static IServiceCollection AddAssembly(this IServiceCollection services, params Assembly[] assemblies)
    {
        if (assemblies==null|assemblies.Count()==0)
        {
            throw new Exception("assemblies cannot be empty.");
        }
        foreach (var assembly in assemblies)
        {
            RegisterDependenciesByAssembly(services, assembly);
            RegisterDependenciesByAssembly(services, assembly);
            RegisterDependenciesByAssembly(services, assembly);
        }
        return services;
    }

    public static void RegisterDependenciesByAssembly(IServiceCollection services, Assembly assembly)
    {            
        var types = assembly.GetTypes().Where(x => typeof(TServiceLifetime).GetTypeInfo().IsAssignableFrom(x) && x.GetTypeInfo().IsClass && !x.GetTypeInfo().IsAbstract && !x.GetTypeInfo().IsSealed).ToList();
        foreach (var type in types)
        {
            var itype = type.GetTypeInfo().GetInterfaces().FirstOrDefault(x => x.Name.ToUpper().Contains(type.Name.ToUpper()));
            if (itype!=null)
            {
                var serviceLifetime = FindServiceLifetime(typeof(TServiceLifetime));
                services.Add(new ServiceDescriptor(itype, type, serviceLifetime));
            }
        }
    }

    private static ServiceLifetime FindServiceLifetime(Type type)
    {
        if (type == typeof(ISingletonDependency))
        {
            return ServiceLifetime.Singleton;
        }
        if (type == typeof(ITransientDependency))
        {
            return ServiceLifetime.Singleton;
        }
        if (type == typeof(ILifetimeScopeDependency))
        {
            return ServiceLifetime.Singleton;
        }

        throw new ArgumentOutOfRangeException($"Provided ServiceLifetime type is invalid. Lifetime:{type.Name}");
    }

    /// 
    /// 注册IocManager
    /// 在ConfigureServices方法最后一行使用
    /// 
    /// 
    public static void AddIocManager(this IServiceCollection services)
    {
        services.AddSingleton(provide =>
        {
            IocManager.Instance.ServiceProvider = provide;
            return IocManager.Instance;
        });
    }
}

4、IocManager使用实例:

4.1、示例程序集

namespace Service
{
    public interface IUserService
    {
        string GetUserNameById(string Id);
    }
    public class UserService:IUserService,ISingletonDependency
    {
        public string GetUserNameById(string Id)
        {
         return "刘大大";
        }
    }
}

4.2、为程序集写一个拓展类

public static class ServiceExtensions
{
    public static IServiceCollection UseService(this IServiceCollection services)
    {
        var assembly = typeof(ServiceExtensions).Assembly;
        services.AddAssembly(assembly);
        return services;
    }
}

4.3、Web层使用

Startup class
       public void ConfigureServices(IServiceCollection services)
        {
           services.UseService();
           
           services.AddControllersWithViews();
           
           services.AddIocManager();
        }
Controller

IIocManager实现了单例模式,可以通过构造器注入获取实例,也可以通过通过IocManager.Instance获取实例

    public class HomeController : Controller
    {
        private readonly IIocManager _iocManager;
        public HomeController(IIocManager iocManager)
        {
            _iocManager = iocManager;
        }
        public string test1()
        {
         //通过注入获取IocManager实例
         var _userService=_iocManager.ServiceProvider.GetService(); 
         var userName=_userService.GetUserNameById("1");
         return userName;
        }
        
        public string test2()
        {
         //通过IocManagerIocManager实例
         var _userService=IocManager.Instance.ServiceProvider.GetService(); 
         var userName=_userService.GetUserNameById("1");
         return userName;
        }
        
        public string test3([FromServices]IUserService _userService)
        {
         //通过注入获取Service实例
         var userName=_userService.GetUserNameById("1");
         return userName;
        }
    }

5、Autofac IocManager实现

5.1、安装 Autofac.Extensions.DependencyInjection包

5.2、 IocManager实现

IIocManager接口

public interface IIocManager
{
    ILifetimeScope ServiceProvider { get; set; }
}

IocManager实现

public class IocManager : IIocManager
{
    static IocManager()
    {
        Instance = new IocManager();
    }
    public static IocManager Instance { get; private set; }
    public ILifetimeScope ServiceProvider { get; set; }
}

静态类 DependencyInjectionExtensions 添加UseIocManager方法。使用Autofac时可以在ConfigureContaine中直接注册内容,ConfigureContainer在ConfigureServices之后运行,

所以不能使用在ConfigureServices里注入IocManager,要在Configure方法中引用IocManager。

/// 
/// 注册IocManager
/// 在Configure方法使用
/// 
/// 
public static IApplicationBuilder UseIocManager(this IApplicationBuilder app)
{
    services.AddSingleton(provide =>
    {
        IocManager.Instance.ServiceProvider = app.ApplicationServices.GetAutofacRoot();
        return app;
    });
}

使用示例:

Startup class
  
  public void ConfigureContainer(ContainerBuilder builder)
  {
      builder.RegisterModule(new AutofacModule());
  }

  public void Configure(IApplicationBuilder app,ILoggerFactory loggerFactory)
  {
      app.UseIocManager();
  }
Controller
public class HomeController : Controller
{
    private readonly IIocManager _iocManager;
    public HomeController(IIocManager iocManager)
    {
        _iocManager = iocManager;
    }
    public string test1()
    {
     //通过注入获取IocManager实例
     var _userService=_iocManager.ServiceProvider.Resolve(); 
     var userName=_userService.GetUserNameById("1");
     return userName;
    }
    
    public string test2()
    {
     //通过IocManager获取IIocManager实例
     var _userService=IocManager.Instance.ServiceProvider.Resolve(); 
     var userName=_userService.GetUserNameById("1");
     return userName;
    }
    
    public string test3([FromServices]IUserService _userService)
    {
     //通过注入获取Service实例
     var userName=_userService.GetUserNameById("1");
     return userName;
    }
}

下载完整源码

ASP.NET Core 3.0 原生DI拓展实现IocManager_第1张图片

你可能感兴趣的:(ASP.NET Core 3.0 原生DI拓展实现IocManager)