autofac official website:
http://autofaccn.readthedocs.io/en/latest/getting-started/index.html
As a popular ioc framework, autofac is still necessary to understand. Here are two small cases to briefly talk about the use of autofac in. net framework console application and asp.net mvc5 project.
Start with the console application.
First, nuget installs autofac and creates a new IDemo interface
namespace AutuFacDemo { interface IDemo { string Hello(); } }
Create a new 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 let's use the mvc5 case.
nuget install Autofac.Mvc5
In the same solution, create a new IBLL and BLL class library, where IBLL stores IDemo.cs:
namespace IBLL { public interface IDemo { string Hello(); } }
BLL store Demo.cs
using IBLL; namespace BLL { public class Demo :IDemo { public string Hello() { return "hello"; } } }
Global.asax.cs configure 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)); } } }
Controller configuration Demo method:
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); } } }
After running, access the Demo method to see the effect.