之前介绍了Unity和Ninject两个IOC容器,但是发现园子里用AutoFac的貌似更为普遍,于是捯饬了两天,发现这个东东确实是个高大上的IOC容器~
Autofac是.NET领域最为流行的IOC框架之一,传说是速度最快的一个:
优点:
既然它都这么牛X了,我们用它就理所当然了,所以推荐其为IOC的终极解决方案!
首先你必须获取AutoFac,这里你可以通过各种方式加载它,我这里还是通过VS中的NuGet来加载AutoFac,不论是哪种方式,最终的目的就是将 Autofac.dll,Autofac.Configuration.dll 这两个程序集引用到你的项目中。这样在你的项目中,如果想使用AutoFac,只需添加其命名空间引用即可~
我们先定义一个数据访问的接口:
public interface IDAL { void Insert(string commandText); }
然后用Sql和Oracle两种方式分别实现上述接口,不过这里只是演示而已,所以并没有真正去实现这两个类,你懂的~
SQL方式:
public class SqlDAL : IDAL { public void Insert(string commandText) { Console.WriteLine("使用sqlDAL添加相关信息"); } }
Oracle方式:
public class OracleDAL : IDAL { public void Insert(string commandText) { Console.WriteLine("使用OracleDAL添加相关信息"); } }
然后注入实现构造函数注入:
public class DBManager {
IDAL _dal; public DBManager(IDAL dal) { _dal= dal; } public void Add(string commandText) { _dal.Insert(commandText); } }
最后要真正完成依赖注入就得AtuoFac登场了:
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')"); }
从以上栗子可以看出,其实AutoFac的使用跟Unity的使用有点像,关键的东东就是这个Container容器类
ContainerBuilder builder = new ContainerBuilder(); builder.RegisterType<SqlDAL>().As<IDAL>(); IContainer container = builder.Build(); SqlDAL sqlDAL = (SqlDAL)container.Resolve<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");
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);
DBManager manager = container.Resolve<DBManager>(new NamedParameter("name", "SQL"));
public class DBManager { IDAL dal; public DBManager (string name,IDAL _dal) { Name = name; dal= _dal; } }
<?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>
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')"); }
终于到了ASP.NET MVC与AtuoFac双剑合璧的时候了,下面就看看AtuoFac在MVC中的应用,其实很简单,大概就几个步骤搞定:
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>(); } } }
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; } } }
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); } }
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); } } }