[转]ASP.NET MVC IOC 之AutoFac攻略

正文转自:http://www.cnblogs.com/WeiGe/p/3871451.html

一、为啥选择AutoFac?

在此以前介绍了Unity和Ninject八个IOC容器,可是发现园子里用AutoFac的貌似更为宽泛,于是捯饬了二日,发现这么些东东实在是个了不起上的IOC容器~

Autofac是.NET领域最佳流行的IOC框架之1,传说是速度最快的2个:

优点: 

  • 它是C#语言调换很紧密,也正是说C#里的浩大编制程序格局都能够为Autofac使用,例如能够用Lambda表明式注册组件
  • 较低的学习曲线,学习它丰裕的简要,只要您知道了IoC和DI的概念以及在何时必要动用它们
  • XML配置协理
  • C语言,电动装配
  • 与Asp.Net MVC 3集成
  • 微软的Orchad开源程序选拔的正是Autofac,从该源码能够看到它的造福和强硬

既然它都那样牛X了,大家用它就自然了,所以推举其为IOC的巅峰消除方案!

二、AutoFac的使用

首先你不能够不得到AutoFac,那里您可以透过各样措施加载它,小编那边还是通过VS中的NuGet来加载AutoFac,不论是哪一类方法,最后的指标便是将
Autofac.dll,Autofac.Configuration.dll
那个程序集引用到您的体系中。那样在你的品类中,假设想利用AutoFac,只需添加其命名空间引用即可~

1、AutoFac入门

作者们先定义3个数额访问的接口:

public interface IDAL
{
    void Insert(string commandText);
}

接下来用Sql和Oracle二种方法分别落成上述接口,可是那里只是演示而已,所以并不曾真的去落到实处那七个类,你懂的~

SQL方式:

C语言 1😉

public class SqlDAL : IDAL
{
    public void Insert(string commandText)
    {
        Console.WriteLine("使用sqlDAL添加相关信息");
    }
}

C语言 2😉

Oracle方式:

C语言 3😉

public class OracleDAL : IDAL
{
    public void Insert(string commandText)
    {
        Console.WriteLine("使用OracleDAL添加相关信息");
    }
}

C语言 4😉

下一场注入完毕构造函数注入:

C语言 5😉

public class DBManager 
{      IDAL _dal;
    public DBManager(IDAL dal) 
    { 
        _dal= dal;
    }
public void Add(string commandText) 
    { 
        _dal.Insert(commandText); 
    }
}

C语言 6😉

最终要真的做到信赖注入就得AtuoFac登场了:

C语言 7😉

var builder = new ContainerBuilder(); 
builder.RegisterType<DBManager>(); 
builder.RegisterType<SqlDAL>().As<IDAL>(); 
using (var container = builder.Build()) 
{ 
    var manager = container.Resolve<DBManager>(); 
    manager.Add("INSERT INTO Persons VALUES ('Man', '25', 'WangW', 'Shanghai')"); 
}

C语言 8😉

从上述栗子能够见见,其实AutoFac的施用跟Unity的施用有点像,关键的东东就是其一Container容器类

二、AutoFac常用艺术求证

(壹)builder.RegisterType<Object>().As<Iobject>():注册连串及其实例。例如上面便是注册接口IDAL的实例SqlDAL

ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<SqlDAL>().As<IDAL>();
IContainer container = builder.Build();
SqlDAL sqlDAL = (SqlDAL)container.Resolve<IDAL>();

(二)IContainer.Resolve<IDAL>():解析有个别接口的实例。例如地点的尾声一行代码正是解析IDAL的实例SqlDAL

(三)builder.RegisterType<Object>().Named<Iobject>(string
name):为三个接口注册分裂的实例。有时候难免会碰到七个类映射同一个接口,比如SqlDAL和OracleDAL都达成了IDAL接口,为了规范获取想要的花色,就非得在注册时起名字。

builder.RegisterType<SqlDAL>().Named<IDAL>("sql");
builder.RegisterType<OracleDAL>().Named<IDAL>("oracle");
IContainer container = builder.Build();
SqlDAL sqlDAL = (SqlDAL)container.ResolveNamed<IDAL>("sql");
OracleDAL oracleDAL = (OracleDAL)container.ResolveNamed<IDAL>("oracle");

(四)IContainer.ResolveNamed<IDAL>(string
name):解析有些接口的“命名实例”。例如地点的末梢壹行代码便是解析IDAL的命名实例OracleDAL

(伍)builder.RegisterType<Object>().Keyed<Iobject>(Enum
enum):以枚举的法子为二个接口注册分化的实例。有时候我们会将某二个接口的两样完毕用枚举来区分,而不是字符串,例如:

public enum DBType{ Sql, Oracle}

builder.RegisterType<SqlDAL>().Keyed<IDAL>(DBType.Sql);
builder.RegisterType<OracleDAL>().Keyed<IDAL>(DBType.Oracle);
IContainer container = builder.Build();
SqlDAL sqlDAL = (SqlDAL)container.ResolveKeyed<IDAL>(DBType.Sql);
OracleDAL oracleDAL = (OracleDAL)container.ResolveKeyed<IDAL>(DBType.Oracle);

(陆)IContainer.ResolveKeyed<IDAL>(Enum
enum):依据枚举值解析有些接口的一定实例。例如地方的尾声一行代码就是解析IDAL的特定实例OracleDAL

(柒)builder.RegisterType<Worker>().InstancePerDependency():用于控制目的的生命周期,每一回加载实例时都以新建3个实例,私下认可正是那种艺术

(八)builder.RegisterType<Worker>().SingleInstance():用于控制目的的生命周期,每一回加载实例时都以回到同1个实例

(九)IContainer.Resolve<T>(NamedParameter
namedParameter):在解析实例T时给其赋值

DBManager manager = container.Resolve<DBManager>(new NamedParameter("name", "SQL"));

C语言 9😉

public class DBManager 
{   
    IDAL dal;
    public DBManager (string name,IDAL  _dal)
    {
        Name = name;
        dal= _dal;
    }
}

C语言 10😉

三、通过配备的点子选拔AutoFac

(一)先配备好布局文件

C语言 11😉

<?xml version="1.0"?>
  <configuration>
    <configSections>
      <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/>
    </configSections>
    <autofac defaultAssembly="ConsoleApplication1">
      <components>
        <component type="ConsoleApplication1.SqlDAL, ConsoleApplication1" service="ConsoleApplication1.IDAL" />
      </components>
    </autofac>
  </configuration>

C语言 12😉

(2)读取配置达成依靠注入(注意引进Autofac.Configuration.dll)

C语言 13😉

static void Main(string[] args)
    {
        ContainerBuilder builder = new ContainerBuilder();
        builder.RegisterType<DBManager>();
        builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
        using (IContainer container = builder.Build())
        {
            DBManager manager = container.Resolve<DBManager>();
            manager.Add("INSERT INTO Persons VALUES ('Man', '25', 'WangW', 'Shanghai')"); 
    } 

C语言 14😉

三、ASP.NET MVC与AtuoFac

到头来到了ASP.NET
MVC与AtuoFac双剑合璧的时候了,上边就看看AtuoFac在MVC中的应用,其实一点也不细略,差不多就几个步骤化解:

一、首先在函数Application_Start() 注册自身的控制器类,一定要引进Autofac.Integration.Mvc.dll

C语言 15😉

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using AtuoFacOfMVC4.Models;
using System.Reflection;
using Autofac.Integration.Mvc;


namespace AtuoFacOfMVC4
{
   public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            var builder = new ContainerBuilder();
            SetupResolveRules(builder);
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            AuthConfig.RegisterAuth();
        }
        private void SetupResolveRules(ContainerBuilder builder)
        {
            builder.RegisterType<StudentRepository>().As<IStudentRepository>();
        }
    }
}

C语言 16😉

2、以往在您的MVC程序中流入注重代码就ok了

(一)首先声喜宝个Student学生类

C语言 17😉

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AtuoFacOfMVC4.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Graduation { get; set; }
        public string School { get; set; }
        public string Major { get; set; }
    }
}

C语言 18😉

(二)然后申明仓库储存接口及其完成

C语言 19😉

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AtuoFacOfMVC4.Models
{
    public interface IStudentRepository
    {
        IEnumerable<Student> GetAll();
        Student Get(int id);
        Student Add(Student item);
        bool Update(Student item);
        bool Delete(int id);
    }
}

C语言 20😉

C语言 21C语言 22

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AtuoFacOfMVC4.Models
{
    public class StudentRepository : IStudentRepository
    {
        private List<Student> Articles = new List<Student>();

        public StudentRepository()
        {
            //添加演示数据
            Add(new Student { Id = 1, Name = "张三", Major = "软件工程", Graduation = "2013年", School = "西安工业大学" });
            Add(new Student { Id = 2, Name = "李四", Major = "计算机科学与技术", Graduation = "2013年", School = "西安工业大学" });
            Add(new Student { Id = 3, Name = "王五", Major = "自动化", Graduation = "2013年", School = "西安工业大学" });
        }
        /// <summary>
        /// 获取全部学生信息
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Student> GetAll()
        {
            return Articles;
        }
        /// <summary>
        /// 通过ID获取学生信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Student Get(int id)
        {
            return Articles.Find(p => p.Id == id);
        }
        /// <summary>
        /// 添加学生信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public Student Add(Student item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            Articles.Add(item);
            return item;
        }
        /// <summary>
        /// 更新学生信息
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public bool Update(Student item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            int index = Articles.FindIndex(p => p.Id == item.Id);
            if (index == -1)
            {
                return false;
            }
            Articles.RemoveAt(index);
            Articles.Add(item);
            return true;
        }
        /// <summary>
        /// 删除学生信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            Articles.RemoveAll(p => p.Id == id);
            return true;
        }
    }
}

View Code

(三)最终添加控制器StudentController,并流入注重代码

C语言 23😉

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AtuoFacOfMVC4.Models;

namespace AtuoFacOfMVC4.Controllers
{
    public class StudentController : Controller
    {
        readonly IStudentRepository repository;
        //构造器注入
        public StudentController(IStudentRepository repository)
        {
            this.repository = repository;
        }

        public ActionResult Index()
        {
            var data = repository.GetAll();
            return View(data);
        }

    }
}

C语言 24😉

(4)最终为控制器StudentController的Index方法添加视图即可,那里不再详述,运维作效果果如下

C语言 25