MVC+IOC+ORM
备注:IOC、AOP、ORM此处只是带过
概念:
MVC请求进来---路由匹配---找到控制器和Action---控制器是个普通的类,Action是个普通的实例方法,系统通过如下方式完成控制器的实例创建:
路由匹配后得到控制器名称---MVCHandler---ControllerBuilder.GetControllerFactory()---然后创建的控制器的实例。
DefaultControllerFactory默认的控制器工厂,通过修改工厂来实现用容器(IOC)创建控制器实例
步骤:
1 继承DefaultControllerFactory
2 SetFactory----实例化控制器会进到这里
3 引入第三方容器--将控制器的实例化换成容器操作
在Global.asax里 ControllerBuilder.Current.SetControllerFactory(new 第三方容器名称());
代码示例:
public class ThirdController : Controller { private IUserService _iUserService = null; private ICompanyService _iCompanyService = null; private IUserCompanyService _iUserCompanyService = null; /// <summary> /// 构造函数注入---控制器得是由容器来实例化 /// </summary> /// <param name="userService"></param> /// <param name="companyService"></param> /// <param name="userCompanyService"></param> public ThirdController(IUserService userService, ICompanyService companyService, IUserCompanyService userCompanyService) { this._iUserService = userService; this._iCompanyService = companyService; this._iUserCompanyService = userCompanyService; } // GET: Third public ActionResult Index() { IUserService service = this._iUserService; User user = service.Find<User>(2); return View(); } }
public class ElevenControllerFactory : DefaultControllerFactory { private Logger logger = new Logger(typeof(ElevenControllerFactory)); protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType) { this.logger.Warn($"{controllerType.Name}被构造..."); IUnityContainer container = DIFactory.GetContainer(); //return base.GetControllerInstance(requestContext, controllerType); return (IController)container.Resolve(controllerType); } }
public class MvcApplication : System.Web.HttpApplication { private Logger logger = new Logger(typeof(MvcApplication)); protected void Application_Start() { AreaRegistration.RegisterAllAreas();//注册区域 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);//注册全局的Filter RouteConfig.RegisterRoutes(RouteTable.Routes);//注册路由 BundleConfig.RegisterBundles(BundleTable.Bundles);//合并压缩 ,打包工具 Combres ControllerBuilder.Current.SetControllerFactory(new ElevenControllerFactory()); this.logger.Info("网站启动了。。。"); } }
原文地址:https://www.cnblogs.com/JohnTang/p/11105374.html
时间: 2024-11-14 11:56:20