autofac官網: http://autofaccn.readthedocs.io/en/latest/getting-started/index.html autofac作為一個熱門ioc框架,還是有瞭解一下的必要的。這裡用兩個小案例來簡單說說autofac在.net framework控制台應 ...
autofac官網:
http://autofaccn.readthedocs.io/en/latest/getting-started/index.html
autofac作為一個熱門ioc框架,還是有瞭解一下的必要的。這裡用兩個小案例來簡單說說autofac在.net framework控制台應用程式和asp.net mvc5 項目中的使用。
先從控制台應用程式開始。
首先nuget安裝autofac,新建IDemo介面
namespace AutuFacDemo { interface IDemo { string Hello(); } }
新建Demo類實現IDemo介面:
namespace AutuFacDemo { public class Demo :IDemo { public string Hello() { return "hello"; } } }
Program.cs:
using Autofac; using System; namespace AutuFacDemo { class Program { private static IContainer Container { set; get; } static void Main(string[] args) { var builder = new ContainerBuilder(); builder.RegisterType<Demo>().As<IDemo>(); Container = builder.Build(); using (var scope = Container.BeginLifetimeScope()) { var demo = scope.Resolve<IDemo>(); Console.WriteLine(demo.Hello()); Console.ReadKey(); } } } }
這樣就完成了一個最簡單的控制台Demo。
現在開始使用mvc5案例。
nuget安裝Autofac.Mvc5
同一解決方案內新建IBLL和BLL類庫,IBLL存放IDemo.cs:
namespace IBLL { public interface IDemo { string Hello(); } }
BLL存放Demo.cs
using IBLL; namespace BLL { public class Demo :IDemo { public string Hello() { return "hello"; } } }
Global.asax.cs配置autofac:
using Autofac; using Autofac.Integration.Mvc; using BLL; using IBLL; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace WebDemo { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(WebApiApplication).Assembly); builder.RegisterType<Demo>().As<IDemo>(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
控制器配置Demo方法:
using IBLL; using System.Web.Mvc; namespace WebDemo.Controllers { public class HomeController : Controller { private IDemo _demo; public HomeController(IDemo demo) { this._demo = demo; } public ActionResult Index() { ViewBag.Title = "Home Page"; return View(); } public ActionResult Demo() { string hello = _demo.Hello(); return Content(hello); } } }
運行後訪問Demo方法,即可看到效果。