Autofc与Mvc,WebForm,Weiapi,Owin整合源码分析

主要分析一下的几个项目:

  Autofac.Integration.Mvc

  Autofac.Integration.WebApi

  Autofac.Integration.Owin

  Autofac.Integration.Web

  Autofac.Integration.WebApi.Owin

  Autofac.Integration.Mvc.Owin

  地址:https://github.com/autofac

以上几个项目分别是 Mvc Webapi Owin 和 webform 与autofac的整合项目

下文将通过对不同的框架进行分别描述,但之前有几个问题需要思考

  什么是ioc

  为什么用ioc

      那么怎么写一个简单ioc该考虑什么?
    1、api 注册 获取
    2、声明周期 单例 瞬时对象 线程唯一 请求唯一等等。。。(待续)
    3、关于gc的思考 ?如何保证对象gc 不会内存溢出
    4、和框架整合需要考虑什么

过去(webform)  

  对于webfrom 来说 一个aspx 窗体 就是一个IHttpHandler, 从webform本身架构来讲 没有设计Ioc容器接口,so aufofac是怎么对这个框架对接的呢?

  通过使用 可以清楚地知道 需要 web.config 配置 ContainerDisposalModule PropertyInjectionModule

  而这2个moduel 分别是干什么的呢。 

    ContainerDisposalModule 很简单 context.EndRequest += OnEndRequest; 对于结束请求释放了请求关联的声明周期你的所有对象 

    PropertyInjectionModule 通俗易懂是 属性输入 ontext.PreRequestHandlerExecute += OnPreRequestHandlerExecute. 在handler初始化成功后将属性注入

  对于webform来说只能使用属性注入,不能使用构造函数注入.why? 因为 前文提到 一个aspx 窗体 就是一个IHttpHandler,至于httphandler在什么时候初始化无法控制。

现在(Mvc WebApi 与Owin混合)

  对于mvc框架和webapi来言 都是mvc模式。本身框架提供了ioc容器入口.

  but 对于mvc的 接口个人非常讨厌。why 因为ioc接口设计相对简陋 未提供dispose,可以想象 一个请求内关联的一个声明周期内的对象 不释放是多么可怕。内存不断地增加。  

  而webapi提供的ioc接口 更好一些 提供了IDependencyScope 提供了 Dispose方法。

  那么对于Mvc是怎么处理请求结束 释放对象的问题呢?

     1、[assembly: PreApplicationStartMethod(typeof(PreApplicationStartCode), "Start")]

     2、DynamicModuleUtility.RegisterModule(typeof(RequestLifetimeHttpModule));

     3、context.EndRequest += OnEndRequest;

     4、ILifetimeScopeProvider.EndLifetimeScope();

  用了net4.0新特性 PreApplicationStartMethod.然后注册了回收方法

  而webapi相对简单:

    AutofacWebApiDependencyScope 内部实现了释放。

  关于2者使用:

    http://docs.autofac.org/en/latest/integration/mvc.html

    http://docs.autofac.org/en/latest/integration/webapi.html

  而关于Owin部分

    因为现在mvc webapi和 owin属于混合 基本上以上使用基本满足。

未来(Owin 坐等net core 版本的owin mvc 和 owin webapi 再补充)

  根据现有的项目来看 经典的Global.asax和web.config 已经见鬼去了。。。。so 再等等吧出正式版再说

  关于Autofac对接Owin,在Autofac.Integration.Owin Autofac.Integration.Mvc.Owin Autofac.Integration.WebApi.Owin这3个项目中autofac封装一套基于Owin管道与Mvc和webapi整合

  例如UseAutofacMiddleware中 将lifetimeScope注入到IOwinContext中

原文地址:https://www.cnblogs.com/rufus-hua/p/5213861.html