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

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

壹 、为啥采用AutoFac?

前边介绍了Unity和Ninject四个IOC容器,不过发现园子里用AutoFac的相似更为普遍,于是捯饬了两日,发现这一个东东确实是个伟大上的IOC容器~

Autofac是.NET领域最为盛行的IOC框架之一,逸事是速度最快的1个:

优点: 

  • 它是C#语言调换很紧密,也等于说C#里的无数编制程序格局都足以为Autofac使用,例如能够用Lambda表达式注册组件
  • 较低的学习曲线,学习它那2个的简要,只要你通晓了IoC和DI的定义以及在几时要求采纳它们
  • XML配置帮衬
  • 电动装配
  • 与Asp.Net MVC 3集成
  • 微软的Orchad开源程序接纳的就是Autofac,从该源码能够观察它的造福和强有力

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

二、AutoFac的使用

率先你不能够不取得AutoFac,那里您能够透过种种艺术加载它,小编那里照旧经过VS中的NuGet来加载AutoFac,不论是哪类方法,末了的指标正是将
Autofac.dll,Autofac.Configuration.dll
那四个程序集引用到您的花色中。那样在你的档次中,假使想行使AutoFac,只需添加其取名空间引用即可~

1、AutoFac入门

咱俩先定义一个数目访问的接口:

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

接下来用Sql和Oracle二种格局分别完毕上述接口,但是那里只是演示而已,所以并没有当真去贯彻那多个类,你懂的~

SQL方式:

Oracle 1😉

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

Oracle 2😉

Oracle方式:

Oracle 3😉

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

Oracle 4😉

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

Oracle 5😉

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

Oracle 6😉

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

Oracle 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')"); 
}

Oracle 8😉

从上述栗子能够见见,其实AutoFac的行使跟Unity的行使有点像,关键的东东就是以此Container容器类

二 、AutoFac常用艺术求证

(1)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>();

(2)IContainer.Resolve<IDAL>():解析某些接口的实例。例如地方的结尾一行代码正是解析IDAL的实例SqlDAL

(3)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");

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

(5)builder.RegisterType<Object>().Keyed<Iobject>(Enum
enum):以枚举的措施为二个接口注册分化的实例。有时候大家会将某3个接口的不等实现用枚举来不一致,而不是字符串,例如:

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);

(6)IContainer.ResolveKeyed<IDAL>(Enum
enum):根据枚举值解析有个别接口的一定实例。例如地点的末尾一行代码正是解析IDAL的特定实例OracleDAL

(7)builder.RegisterType<Worker>().InstancePerDependency():用于控制指标的生命周期,每一回加载实例时皆以新建3个实例,私下认可正是那种办法

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

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

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

Oracle 9😉

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

Oracle 10😉

叁 、通过铺排的方法接纳AutoFac

(1)先配备好布局文件

Oracle 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>

Oracle 12😉

(2)读取配置完结依靠注入(注意引入Autofac.Configuration.dll)

Oracle 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')"); 
    } 

Oracle 14😉

三、ASP.NET MVC与AtuoFac

好不不难到了ASP.NET
MVC与AtuoFac双剑合璧的时候了,上面就看看AtuoFac在MVC中的应用,其实很简短,大致就几个步骤消除:

壹 、首先在函数Application_Start() 注册本人的主宰器类,一定要引入Autofac.Integration.Mvc.dll

Oracle 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>();
        }
    }
}

Oracle 16😉

二 、未来在您的MVC程序中注入倚重代码就ok了

(1)首先声美素佳儿个Student学生类

Oracle 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; }
    }
}

Oracle 18😉

(2)然后证明仓库储存接口及其达成

Oracle 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);
    }
}

Oracle 20😉

Oracle 21Oracle 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

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

Oracle 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);
        }

    }
}

Oracle 24😉

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

Oracle 25

 

相关文章