故事背景

最近在把自己的一个老项目从framework迁移到.net core 3.0,数据访问这块选择的是efcore+mysql。使用ef的话不可避免要和dbcontext打交道,在core中的常规用法一般是:创建一个xxxcontext类继承自dbcontext,实现一个拥有dbcontextoptions参数的构造器,在启动类startup中的configureservices方法里调用iservicecollection的扩展方法adddbcontext,把上下文注入到di容器中,然后在使用的地方通过构造函数的参数获取实例。ok,没任何毛病,官方示例也都是这么来用的。但是,通过构造函数这种方式来获取上下文实例其实很不方便,比如在attribute或者静态类中,又或者是系统启动时初始化一些数据,更多的是如下一种场景:

public class basecontroller : controller
  {
    public bloggingcontext _dbcontext;
    public basecontroller(bloggingcontext dbcontext)
    {
      _dbcontext = dbcontext;
    }

    public bool blogexist(int id)
    {
      return _dbcontext.blogs.any(x => x.blogid == id);
    }
  }

  public class blogscontroller : basecontroller
  {
    public blogscontroller(bloggingcontext dbcontext) : base(dbcontext) { }
  }

从上面的代码可以看到,任何要继承basecontroller的类都要写一个“多余”的构造函数,如果参数再多几个,这将是无法忍受的(就算只有一个参数我也忍受不了)。那么怎样才能更优雅的获取数据库上下文实例呢,我想到以下几种办法。

dbcontext从哪来

1、 直接开溜new

回归原始,既然要创建实例,没有比直接new一个更好的办法了,在framework中没有di的时候也差不多都这么干。但在efcore中不同的是,dbcontext不再提供无参构造函数,取而代之的是必须传入一个dbcontextoptions类型的参数,这个参数通常是做一些上下文选项配置例如使用什么类型数据库连接字符串是多少。

 public bloggingcontext(dbcontextoptions<bloggingcontext> options) : base(options)
    {
    }

默认情况下,我们已经在startup中注册上下文的时候做了配置,di容器会自动帮我们把options传进来。如果要手动new一个上下文,那岂不是每次都要自己传?不行,这太痛苦了。那有没有办法不传这个参数?肯定也是有的。我们可以去掉有参构造函数,然后重写dbcontext中的onconfiguring方法,在这个方法中做数据库配置:

  protected override void onconfiguring(dbcontextoptionsbuilder optionsbuilder)
    {
      optionsbuilder.usesqlite("filename=./efcoredemo.db");
    }

即使是这样,依然有不够优雅的地方,那就是连接字符串被硬编码在代码中,不能做到从配置文件读取。反正我忍受不了,只能再寻找其他方案。

2、 从di容器手动获取

既然前面已经在启动类中注册了上下文,那么从di容器中获取实例肯定是没问题的。于是我写了这样一句测试代码用来验证猜想:

 var context = app.applicationservices.getservice<bloggingcontext>();

不过很遗憾抛出了异常:

报错信息说的很明确,不能从root provider中获取这个服务。我从g站下载了di框架的源码(地址是https://github.com/aspnet/extensions/tree/master/src/dependencyinjection),拿报错信息进行反向追溯,发现异常来自于callsitevalidator类的validateresolution方法:

public void validateresolution(type servicetype, iservicescope scope, iservicescope rootscope)
    {
      if (referenceequals(scope, rootscope)
        && _scopedservices.trygetvalue(servicetype, out var scopedservice))
      {
        if (servicetype == scopedservice)
        {
          throw new invalidoperationexception(
            resources.formatdirectscopedresolvedfromrootexception(servicetype,
              nameof(servicelifetime.scoped).tolowerinvariant()));
        }

        throw new invalidoperationexception(
          resources.formatscopedresolvedfromrootexception(
            servicetype,
            scopedservice,
            nameof(servicelifetime.scoped).tolowerinvariant()));
      }
    }

继续往上,看到了getservice方法的实现:

internal object getservice(type servicetype, serviceproviderenginescope serviceproviderenginescope)
    {
      if (_disposed)
      {
        throwhelper.throwobjectdisposedexception();
      }

      var realizedservice = realizedservices.getoradd(servicetype, _createserviceaccessor);
      _callback?.onresolve(servicetype, serviceproviderenginescope);
      dependencyinjectioneventsource.log.serviceresolved(servicetype);
      return realizedservice.invoke(serviceproviderenginescope);
    }

可以看到,_callback在为空的情况下是不会做验证的,于是猜想有参数能对它进行配置。把追溯对象换成_callback继续往上翻,在di框架的核心类serviceprovider中找到如下方法:

internal serviceprovider(ienumerable<servicedescriptor> servicedescriptors, serviceprovideroptions options)
    {
      iserviceproviderenginecallback callback = null;
      if (options.validatescopes)
      {
        callback = this;
        _callsitevalidator = new callsitevalidator();
      }
      //省略....
    }

说明我的猜想没错,验证是受validatescopes控制的。这样来看,把validatescopes设置成false就可以解决了,这也是网上普遍的解决方案:

 .usedefaultserviceprovider(options =>
    {
       options.validatescopes = false;
    })

但这样做是极其危险的。

为什么危险?到底什么是root provider?那就要从原生di的生命周期说起。我们知道,di容器被封装成一个iserviceprovider对象,服务都是从这里来获取。不过这并不是一个单一对象,它是具有层级结构的,最顶层的即前面提到的root provider,可以理解为仅属于系统层面的di控制中心。在asp.net core中,内置的di有3种服务模式,分别是singleton、transient、scoped,singleton服务实例是保存在root provider中的,所以它才能做到全局单例。相对应的scoped,是保存在某一个provider中的,它能保证在这个provider中是单例的,而transient服务则是随时需要随时创建,用完就丢弃。由此可知,除非是在root provider中获取一个单例服务,否则必须要指定一个服务范围(scope),这个验证是通过serviceprovideroptions的validatescopes来控制的。默认情况下,asp.net core框架在创建hostbuilder的时候会判定当前是否开发环境,在开发环境下会开启这个验证:

所以前面那种关闭验证的方式是错误的。这是因为,root provider只有一个,如果恰好有某个singleton服务引用了一个scope服务,这会导致这个scope服务也变成singleton,仔细看一下注册dbcontext的扩展方法,它实际上提供的是scope服务:

如果发生这种情况,数据库连接会一直得不到释放,至于有什么后果大家应该都明白。

所以前面的测试代码应该这样写:

  using (var servicescope = app.applicationservices.createscope())
   {
     var context = servicescope.serviceprovider.getservice<bloggingcontext>();
   }

与之相关的还有一个validateonbuild属性,也就是说在构建iserviceprovider的时候就会做验证,从源码中也能体现出来:

if (options.validateonbuild)
      {
        list<exception> exceptions = null;
        foreach (var servicedescriptor in servicedescriptors)
        {
          try
          {
            _engine.validateservice(servicedescriptor);
          }
          catch (exception e)
          {
            exceptions = exceptions ?? new list<exception>();
            exceptions.add(e);
          }
        }

        if (exceptions != null)
        {
          throw new aggregateexception("some services are not able to be constructed", exceptions.toarray());
        }
      }

正因为如此,asp.net core在设计的时候为每个请求创建独立的scope,这个scope的provider被封装在httpcontext.requestservices中。

[小插曲]

通过代码提示可以看到,iserviceprovider提供了2种获取service的方式:

这2个有什么区别呢?分别查看各自的方法摘要可以看到,通过getservice获取一个没有注册的服务时会返回null,而getrequiredservice会抛出一个invalidoperationexception,仅此而已。

// 返回结果:
    //   a service object of type t or null if there is no such service.
    public static t getservice<t>(this iserviceprovider provider);

    // 返回结果:
    //   a service object of type t.
    //
    // 异常:
    //  t:system.invalidoperationexception:
    //   there is no service of type t.
    public static t getrequiredservice<t>(this iserviceprovider provider);

终极大招

到现在为止,尽管找到了一种看起来合理的方案,但还是不够优雅,使用过其他第三方di框架的朋友应该知道,属性注入的快感无可比拟。那原生di有没有实现这个功能呢,我满心欢喜上g站搜issue,看到这样一个回复(https://github.com/aspnet/extensions/issues/2406):

官方明确表示没有开发属性注入的计划,没办法,只能靠自己了。

我的思路大概是:创建一个自定义标签(attribute),用来给需要注入的属性打标签,然后写一个服务激活类,用来解析给定实例需要注入的属性并赋值,在某个类型被创建实例的时候也就是构造函数中调用这个激活方法实现属性注入。这里有个核心点要注意的是,从di容器获取实例的时候一定要保证是和当前请求是同一个scope,也就是说,必须要从当前的httpcontext中拿到这个iserviceprovider。

先创建一个自定义标签:

  [attributeusage(attributetargets.property)]
  public class autowiredattribute : attribute
  {

  }

解析属性的方法:

public void propertyactivate(object service, iserviceprovider provider)
    {
      var servicetype = service.gettype();
      var properties = servicetype.getproperties().asenumerable().where(x => x.name.startswith("_"));
      foreach (propertyinfo property in properties)
      {
        var autowiredattr = property.getcustomattribute<autowiredattribute>();
        if (autowiredattr != null)
        {
          //从di容器获取实例
          var innerservice = provider.getservice(property.propertytype);
          if (innerservice != null)
          {
            //递归解决服务嵌套问题
            propertyactivate(innerservice, provider);
            //属性赋值
            property.setvalue(service, innerservice);
          }
        }
      }
    }

然后在控制器中激活属性:

[autowired]
    public iaccountservice _accountservice { get; set; }

    public logincontroller(ihttpcontextaccessor httpcontextaccessor)
    {
      var pro = new autowiredserviceprovider();
      pro.propertyactivate(this, httpcontextaccessor.httpcontext.requestservices);
    }

这样子下来,虽然功能实现了,但是里面存着几个问题。第一个是由于控制器的构造函数中不能直接使用controllerbase的httpcontext属性,所以必须要通过注入ihttpcontextaccessor对象来获取,貌似问题又回到原点。第二个是每个构造函数中都要写这么一堆代码,不能忍。于是想有没有办法在控制器被激活的时候做一些操作?没考虑引入aop框架,感觉为了这一个功能引入aop有点重。经过网上搜索,发现asp.net core框架激活控制器是通过icontrolleractivator接口实现的,它的默认实现是defaultcontrolleractivator(https://github.com/aspnet/aspnetcore/blob/master/src/mvc/mvc.core/src/controllers/defaultcontrolleractivator.cs):

/// <inheritdoc />
    public object create(controllercontext controllercontext)
    {
      if (controllercontext == null)
      {
        throw new argumentnullexception(nameof(controllercontext));
      }

      if (controllercontext.actiondescriptor == null)
      {
        throw new argumentexception(resources.formatpropertyoftypecannotbenull(
          nameof(controllercontext.actiondescriptor),
          nameof(controllercontext)));
      }

      var controllertypeinfo = controllercontext.actiondescriptor.controllertypeinfo;

      if (controllertypeinfo == null)
      {
        throw new argumentexception(resources.formatpropertyoftypecannotbenull(
          nameof(controllercontext.actiondescriptor.controllertypeinfo),
          nameof(controllercontext.actiondescriptor)));
      }

      var serviceprovider = controllercontext.httpcontext.requestservices;
      return _typeactivatorcache.createinstance<object>(serviceprovider, controllertypeinfo.astype());
    }

这样一来,我自己实现一个controller激活器不就可以接管控制器激活了,于是有如下这个类:

public class hoscontrolleractivator : icontrolleractivator
  {
    public object create(controllercontext actioncontext)
    {
      var controllertype = actioncontext.actiondescriptor.controllertypeinfo.astype();
      var instance = actioncontext.httpcontext.requestservices.getrequiredservice(controllertype);
      propertyactivate(instance, actioncontext.httpcontext.requestservices);
      return instance;
    }

    public virtual void release(controllercontext context, object controller)
    {
      if (context == null)
      {
        throw new argumentnullexception(nameof(context));
      }
      if (controller == null)
      {
        throw new argumentnullexception(nameof(controller));
      }
      if (controller is idisposable disposable)
      {
        disposable.dispose();
      }
    }

    private void propertyactivate(object service, iserviceprovider provider)
    {
      var servicetype = service.gettype();
      var properties = servicetype.getproperties().asenumerable().where(x => x.name.startswith("_"));
      foreach (propertyinfo property in properties)
      {
        var autowiredattr = property.getcustomattribute<autowiredattribute>();
        if (autowiredattr != null)
        {
          //从di容器获取实例
          var innerservice = provider.getservice(property.propertytype);
          if (innerservice != null)
          {
            //递归解决服务嵌套问题
            propertyactivate(innerservice, provider);
            //属性赋值
            property.setvalue(service, innerservice);
          }
        }
      }
    }
  }

需要注意的是,defaultcontrolleractivator中的控制器实例是从typeactivatorcache获取的,而自己的激活器是从di获取的,所以必须额外把系统所有控制器注册到di中,封装成如下的扩展方法:

/// <summary>
    /// 自定义控制器激活,并手动注册所有控制器
    /// </summary>
    /// <param name="services"></param>
    /// <param name="obj"></param>
    public static void addhoscontrollers(this iservicecollection services, object obj)
    {
      services.replace(servicedescriptor.transient<icontrolleractivator, hoscontrolleractivator>());
      var assembly = obj.gettype().gettypeinfo().assembly;
      var manager = new applicationpartmanager();
      manager.applicationparts.add(new assemblypart(assembly));
      manager.featureproviders.add(new controllerfeatureprovider());
      var feature = new controllerfeature();
      manager.populatefeature(feature);
      feature.controllers.select(ti => ti.astype()).tolist().foreach(t =>
      {
        services.addtransient(t);
      });
    }

在configureservices中调用:

services.addhoscontrollers(this);

到此,大功告成!可以愉快的继续crud了。

结尾

市面上好用的di框架一堆一堆的,集成到core里面也很简单,为啥还要这么折腾?没办法,这不就是造轮子的乐趣嘛。上面这些东西从头到尾也折腾了不少时间,属性注入那里也还有优化的空间,欢迎探讨。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。