autofac 用法总结
autofac 用法总结
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方法,即可看到效果。


浙公网安备 33010602011771号