欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-05 20:23:21
昨天 .NET Core 3.0 正式发布,创建一个项目运行后发现:原来使用的Autofac在ConfigureServices返回IServiceProvider的这种写法已经不再支持。 当然Autofac官方也给出了示例。.NET Core 本身内置DI,我决定不再使用Autofac,就使用原生 ......

昨天.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<startup>();
        })
        .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、创建生命周期接口

    /// <summary>
    ///    标记依赖项生命周期的接口
    ///     <see cref="ilifetimescopedependency" />,
    ///     <see cref="itransientdependency" />,
    ///     <see cref="isingletondependency" />
    /// </summary>
    public interface ilifetime { }
    /// <summary>
    /// 确定接口或类的生存期
    /// 作用域模式,服务在每次请求时被创建,整个请求过程中都贯穿使用这个创建的服务。
    /// </summary>
    public interface ilifetimescopedependency : ilifetime { }
    /// <summary>
    /// 确定接口或类的生存期
    /// 作用域模式,服务在每次请求时被创建,整个请求过程中都贯穿使用这个创建的服务。
    /// </summary>
    public interface ilifetimescopedependency : ilifetime { }
    /// <summary>
    /// 确定接口或类的生存期
    /// 瞬态模式,每次请求时都会创建。
    /// </summary>
    public interface itransientdependency : ilifetime { }

3、拓展iservicecollection

/// <summary>
/// .net core 依赖注入拓展
/// </summary>
public static class dependencyinjectionextensions
{
    /// <summary>
    /// 注册程序集组件
    /// </summary>
    /// <param name="services"></param>
    /// <param name="assemblies"></param>
    /// <returns></returns>
    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<isingletondependency>(services, assembly);
            registerdependenciesbyassembly<itransientdependency>(services, assembly);
            registerdependenciesbyassembly<ilifetimescopedependency>(services, assembly);
        }
        return services;
    }

    public static void registerdependenciesbyassembly<tservicelifetime>(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}");
    }

    /// <summary>
    /// 注册iocmanager
    /// 在configureservices方法最后一行使用
    /// </summary>
    /// <param name="services"></param>
    public static void addiocmanager(this iservicecollection services)
    {
        services.addsingleton<iiocmanager, iocmanager>(provide =>
        {
            iocmanager.instance.serviceprovider = provide;
            return iocmanager.instance;
        });
    }
}

4、iocmanager使用实例:

4.1、示例程序集

namespace service
{
    public interface iuserservice
    {
        string getusernamebyid(string id);
    }
    public interface 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<iuserservice>(); 
         var username=_userservice.getusernamebyid("1");
         return username;
        }
        
        public string test2()
        {
         //通过iocmanager获取iiocmanager实例
         var _userservice=iocmanager.instance.serviceprovider.getservice<iuserservice>(); 
         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。

/// <summary>
/// 注册iocmanager
/// 在configure方法使用
/// </summary>
/// <param name="services"></param>
public static iapplicationbuilder useiocmanager(this iapplicationbuilder app)
{
    services.addsingleton<iiocmanager, iocmanager>(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<iuserservice>(); 
     var username=_userservice.getusernamebyid("1");
     return username;
    }
    
    public string test2()
    {
     //通过iocmanager获取iiocmanager实例
     var _userservice=iocmanager.instance.serviceprovider.resolve<iuserservice>(); 
     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