在我这个框架中需要引用一下几个dll

Autofac,Autofac.Configuration,Autofac.Mvc4,Autofac.WebApi


配置方面我用的是XML文件配置

在添加完引用之后,就可以配置了!下面是配置代码! 首先要弄清楚,整个MyautoFac.Web的程序入口Global.asax.cs文件中的Application_Start()方法里

 public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AutofacRegister.Register();//常规注入 -------》App_Start 文件夹下

         }

    }


App_Start 文件夹下 代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Mvc;
using Autofac;
using Autofac.Configuration;
using Autofac.Integration.Mvc;


namespace SupervisionWin.Web
{
    public class AutofacRegister
    {
        public static void Register()
        {
            var builder = new ContainerBuilder();


            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
            builder.RegisterSource(new ViewRegistrationSource());//页面注入
            builder.RegisterFilterProvider();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
        }
    }
}


XML 配置

 然后在Web.config里填代码!如下:

        <configSections>

           <!--注册autofac节点,在此之前需要引入Autofac.Configuration-->

           <section name="autofac"type="Autofac.Configuration.SectionHandler,Autofac.Configuration"/> 

        </configSections>

         <!--autofac节点的属性设置-->

         <autofac>

           <!--这个部分之前我尝试过直接注入,可是后来发现一个问题就是,有时候不会被识别,所以我尝试分别注入每个类库,其中name属性是相对路径-->

           <files>

             <!--关于section属性,是文件中的autoFac节点-->

             <file name="..//MyAutoFac.Service/Configuration.config"section="autoFac"></file>

             <filename="..//MyAutoFac.Repository/Configuration.config"section="autoFac"></file>

           </files>

          </autofac>




      至于Configuration.config文件,我只举一个例子说明!单独新建一个

       <configSections>

         <section name="autoFac"type="Autofac.Configuration.SectionHandler,Autofac.Configuration"/>

       </configSections>

        <!--defaultAssemby属性是非必须属性,但是我喜欢把它加上,为了防止出错-->

        <autoFacdefaultAssembly="MyAutoFac.Service">

          <!--这个component节点就是依赖注入的配置部分 type属性是MyAutoFac.Service中的User文件还有命名空间-->

         <components>

            <!--之后的service属性是指的MyAutoFac.Service.IService.UserService文件-->

           <componenttype="MyAutoFac.Service.UserService, MyAutoFac.Service" service="MyAutoFac.Service.IService.IUserService"/>

         </components>

        </autoFac>