1、解压它的压缩包,主要看到Autofac.dll,Autofac.Configuration.dll,这也是本篇文章重点使用的Autofac的类库。
2、引用->添加引用
3、定义接口,类
public interface ILog { void SaveLog(string message); } public class TxtLog : ILog { public void SaveLog(string message) { throw new NotImplementedException(); } } public class DbLog : ILog { public void SaveLog(string message) { throw new NotImplementedException(); } }
4、在 Global.asax 的 Application_Start() 上注册服务
using Autofac;
using Autofac.Integration.Mvc;
using System.Reflection;
protected void Application_Start() { //......... //第一步:创建ContainerBuilder对象。 ContainerBuilder builder = new ContainerBuilder(); //第二步:注册服务(注册Controller类,注册程序集,注册类型) builder.RegisterControllers(Assembly.GetExecutingAssembly());//注册了当前程序集内所有的Controller类 builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly())//注册了当前程序集内的所有类 .AsImplementedInterfaces(); builder.RegisterType<DbLog>().As<ILog>(); //可看出ILog的类型已变成了DbLog。但为何要强调末端处?实际上,DBLog已经通过builder.RegisterAssemblyTypes被注册过一次,如果对同一个类型或接口注册多次(比如这里的ILog),在Autofac中会以列表的形式保存,如果只取一个,则Autofac会从列表返回最新的那个。 //第三步:创建容器 var container = builder.Build(); //第四步:用AutofacDependencyResolver替换MVC默认的DependencyResolver DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }
5、Controller 方法
public class HomeController : Controller { private ILog _log; private IEnumerable<ILog> _logList; public HomeController(ILog log,IEnumerable<ILog> logList) { _log = log; _logList = logList; } public ActionResult Index() { ViewBag.Message = "Welcome to ASP.NET MVC!"; ViewBag.LogTypeName = _log.GetType().Name; ViewBag.LogTypeNames = _logList.Select(x => x.GetType().Name).Aggregate((x,y) => x + "," + y); return View(); } }
6、View
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Index</title> </head> <body> <div> Autofac会从列表返回最新的那个: @ViewBag.LogTypeName </div> <div> 同一个类型或接口注册多次(比如这里的ILog),在Autofac中会以列表的形式保存(第一个,是最后也个注册的对象):@ViewBag.LogTypeNames </div> </body> </html>
7、效果: