Autofac usage Summary
Official autofac Website:
Http://autofaccn.readthedocs.io/en/latest/getting-started/index.html
As a popular ioc framework, autofac is necessary to understand. Here we will use two small cases to briefly describe how to use autofac In the. net framework console application and asp.net mvc5 project.
Start with the console application.
First, install autofac in nuget and create the IDemo interface.
namespace AutuFacDemo{ interface IDemo { string Hello(); }}
Create a Demo class to implement the IDemo interface:
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(); } } }}
This completes the simplest console Demo.
Now we start to use the mvc5 case.
Install Autofac. Mvc5 in nuget
Create the IBLL and BLL class libraries in the same solution, and IBLL stores IDemo. cs:
namespace IBLL{ public interface IDemo { string Hello(); }}
BLL stores Demo. cs
using IBLL;namespace BLL{ public class Demo :IDemo { public string Hello() { return "hello"; } }}
Configure autofac for Global. asax. cs:
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 Method for controller Configuration:
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); } }}
Access the Demo method after running to see the effect.