Autofac在mvc 3中的使用
Autofac在mvc 3中的使用
1、直接集成
引入Autofac.dll,Autofac.Configuration.dll
private void SetupResolveRules(ContainerBuilder builder) { //Components are wired to services using the As() methods on ContainerBuilder builder.RegisterType<SysUserMgrImp>().As<ISysUserMgr>(); builder.RegisterType<FormsAuthServiceImp>().As<IFormsAuthService>(); } protected void Application_Start() { // 依赖注入 var builder = new ContainerBuilder(); SetupResolveRules(builder); builder.RegisterControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); }
使用构造函数注入
public class SysUserController : AdminBaseController { private ISysUserMgr sysUserMgr;// = new SysUserMgrImp(); public SysUserController(ISysUserMgr mgr) { sysUserMgr = mgr; } ............................
2、配置文件
引入Autofac.dll,Autofac.Configuration.dll,Autofac.Configuration.dll
修改web.config
<configSections> <section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/> </configSections> <autofac defaultAssembly="GPS.Domain"> <components> <component type="GPS.Domain.Implements.SysUserMgrImp,GPS.Domain.Implements" service="GPS.Domain.Interfaces.ISysUserMgr" /> <component type="GPS.Domain.Implements.FormsAuthServiceImp,GPS.Domain.Implements" service="GPS.Domain.Interfaces.IFormsAuthService" > </component> </components> </autofac>
修改Global.asax
protected void Application_Start() { // 依赖注入 var builder = new ContainerBuilder(); builder.RegisterModule(new ConfigurationSettingsReader("autofac")); builder.RegisterControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); }
使用构造函数注入
public class AccountController : Controller { private ISysUserMgr sysUserMgr;// = new SysUserMgrImp(); private IFormsAuthService formAuthService;// = new FormsAuthServiceImp(); public AccountController(ISysUserMgr userMgr, IFormsAuthService formAuth) { sysUserMgr = userMgr; formAuthService = formAuth; } ........................
参考
http://code.google.com/p/autofac/wiki/Mvc3Integration
http://code.google.com/p/autofac/wiki/XmlConfiguration
作者:深潭
出处:http://www.cnblogs.com/dbasys/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/dbasys/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。