public MefControllerFactory(string pluginPath)
 {
     this._pluginPath = pluginPath;
     this._catalog = new DirectoryCatalog(pluginPath);
     this._container = new CompositionContainer(_catalog);
     this._defaultControllerFactory = new DefaultControllerFactory();
 }
Пример #2
0
        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            /// 取得Spring的对象
            WebApplicationContext ctx = ContextRegistry.GetContext() as WebApplicationContext;
            string controller = controllerName + "Controller";

            /// <c>查找是否配置该Controller</c>如果没有将Controller配置到Spring中去的话,在这儿就检测不到controllerName,所以调用else来实例化Controller,但同时Controller的属性不会被实例化
            ///file://~/Configuration/Controllers.xml
            if (ctx.ContainsObject(controller))
            {
                object controllerf = ctx.GetObject(controller);
                return (IController)controllerf;

            }
            else
            {
                if (defalutf == null)
                {
                    defalutf = new DefaultControllerFactory();
                }

                // 如果Controller没有配置到Spring的xml文件中,调用这句开始实例化想要的Controller,可以给Controller添加断点跟踪
                return defalutf.CreateController(requestContext, controllerName);
            }
        }
Пример #3
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            NinjectControllerActivator controllerActivator = new NinjectControllerActivator();
            controllerActivator.Register<IEmployeeRepository, EmployeeRepository>();
            DefaultControllerFactory controllerFactory = new DefaultControllerFactory(controllerActivator);
            ControllerBuilder.Current.SetControllerFactory(controllerFactory);
        }
        /// <summary>
        /// Maps the attribute-defined routes for the application.
        /// </summary>
        /// <param name="routes"></param>
        /// <param name="constraintResolver">The <see cref="IInlineConstraintResolver"/> to use for resolving inline constraints in route templates.</param>
        public static void MapMvcAttributeRoutes(this RouteCollection routes, IInlineConstraintResolver constraintResolver)
        {
            DefaultControllerFactory typesLocator =
                DependencyResolver.Current.GetService <IControllerFactory>() as DefaultControllerFactory
                ?? ControllerBuilder.Current.GetControllerFactory() as DefaultControllerFactory
                ?? new DefaultControllerFactory();

            IReadOnlyList <Type> controllerTypes = typesLocator.GetControllerTypes();

            MapMvcAttributeRoutes(routes, controllerTypes, constraintResolver);
        }
Пример #5
0
        public void CreateControllerWithFactoryInstanceReturnsInstance() {
            // Arrange
            ControllerBuilder cb = new ControllerBuilder();
            DefaultControllerFactory factory = new DefaultControllerFactory();
            cb.SetControllerFactory(factory);

            // Act
            IControllerFactory cf = cb.GetControllerFactory();

            // Assert
            Assert.AreSame(factory, cf);
        }
 public IController CreateController(RequestContext requestContext, string controllerName)
 {
     if (controllerName.ToLower().StartsWith("proteintracker"))
       {
     var repository = new ProteinRespository();
     var service = new ProteinTrackingService(repository);
     var controller = new ProteinTrackerController(service);
     return controller;
       }
       var defaultFactory = new DefaultControllerFactory();
       return defaultFactory.CreateController(requestContext, controllerName);
 }
        public void DisposeControllerFactoryWithDisposableController() {
            // Arrange
            IControllerFactory factory = new DefaultControllerFactory();
            Mock<ControllerBase> mockController = new Mock<ControllerBase>();
            IMock<IDisposable> mockDisposable = mockController.As<IDisposable>();
            mockDisposable.Expect(d => d.Dispose()).Verifiable();

            // Act
            factory.ReleaseController(mockController.Object);

            // Assert
            mockDisposable.Verify();
        }
        public void CreateControllerWithNullContextThrows() {
            // Arrange
            DefaultControllerFactory factory = new DefaultControllerFactory();

            // Act
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                    ((IControllerFactory)factory).CreateController(
                        null,
                        "foo");
                },
                "requestContext");
        }
        public void CreateControllerWithEmptyControllerNameThrows() {
            // Arrange
            DefaultControllerFactory factory = new DefaultControllerFactory();

            // Act
            ExceptionHelper.ExpectArgumentException(
                delegate {
                    ((IControllerFactory)factory).CreateController(
                        new RequestContext(new Mock<HttpContextBase>().Object, new RouteData()),
                        String.Empty);
                },
                "Value cannot be null or empty.\r\nParameter name: controllerName");
        }
Пример #10
0
        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            if (controllerName.ToLower().StartsWith("home"))
            {
                ISpeakerService service = new SpeakersRepository();
                IController controller = new HomeController(service);

                return controller;
            }

            IControllerFactory factory = new DefaultControllerFactory();
            return factory.CreateController(requestContext, controllerName);
        }
        public void ReleaseController(IController controller)
        {
            //get spring context
            IApplicationContext ctx = ContextRegistry.GetContext();
            if (!ctx.ContainsObject(controller.GetType().Name))
            {
                if (defalutf == null)
                {
                    defalutf = new DefaultControllerFactory();
                }

                defalutf.ReleaseController(controller);
            }
        }
Пример #12
0
        //This method checks if we have an AJAX request or not
        private bool IsAjaxRequest()
        {
            //The easy way
            bool isAjaxRequest = (Request["X-Requested-With"] == "XMLHttpRequest")
            || ((Request.Headers != null)
            && (Request.Headers["X-Requested-With"] == "XMLHttpRequest"));

            //If we are not sure that we have an AJAX request or that we have to return JSON
            //we fall back to Reflection
            if (!isAjaxRequest)
            {
                try
                {
                    //The controller and action
                    string controllerName = Request.RequestContext.
                                            RouteData.Values["controller"].ToString();
                    string actionName = Request.RequestContext.
                                        RouteData.Values["action"].ToString();

                    //We create a controller instance
                    DefaultControllerFactory controllerFactory = new DefaultControllerFactory();
                    Controller controller = controllerFactory.CreateController(
                    Request.RequestContext, controllerName) as Controller;

                    //We get the controller actions
                    ReflectedControllerDescriptor controllerDescriptor =
                    new ReflectedControllerDescriptor(controller.GetType());
                    ActionDescriptor[] controllerActions =
                    controllerDescriptor.GetCanonicalActions();

                    //We search for our action
                    foreach (ReflectedActionDescriptor actionDescriptor in controllerActions)
                    {
                        if (actionDescriptor.ActionName.ToUpper().Equals(actionName.ToUpper()))
                        {
                            //If the action returns JsonResult then we have an AJAX request
                            if (actionDescriptor.MethodInfo.ReturnType
                                .Equals(typeof(JsonResult)))
                                return true;
                        }
                    }
                }
                catch(Exception eeee)
                {
                    log.Exception(eeee);
                }
            }

            return isAjaxRequest;
        }
Пример #13
0
        public ActionResult Yes(ConfirmationActionViewModel model)
        {
            if (!model.HttpPost)
                return Redirect(model.YesUrl);

            ConfirmationData data = ConfirmationService.GetData(model.Id);

            RouteData route = RoutesHelper.GetRouteDataByUrl("/" + model.YesUrl);

            //var controllerDescriptor = new ReflectedControllerDescriptor(GetType());
            string controllerName = (String)route.Values["controller"];
            string actionName = (String)route.Values["action"];
            //string values = RouteData.GetRequiredString("id");

            //IControllerActivator
            DefaultControllerFactory d = new DefaultControllerFactory();

            IController controller = d.CreateController(HttpContext.Request.RequestContext, controllerName);

            ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(controller.GetType());
            //d.ReleaseController(controller);

            ActionDescriptor actionDescriptor = controllerDescriptor.FindAction(ControllerContext, actionName);

            RequestContext requestContext = new RequestContext(new RoutesHelper.RewritedHttpContextBase("/" + model.YesUrl), route);

            requestContext.HttpContext.Request.Form.Add((NameValueCollection)data.PostData);

            ControllerContext ctx = new ControllerContext(requestContext, (ControllerBase)controller);
            IDictionary<string, object> parameters2 = GetParameterValues(ctx, actionDescriptor);
            IDictionary<string, object> parameters = new Dictionary<string,object>();

            ControllerContext.HttpContext.Response.Clear();
            NameValueCollection nameValueCollection = data.PostData as NameValueCollection;
            //nameValueCollection.
            actionDescriptor.Execute(ControllerContext, (IDictionary<string, object>)data.PostData);

            //var viewResult = new ViewResult
            //{
            //    ViewName = "",
            //    MasterName = "",
            //    ViewData = new ViewDataDictionary(data.PostData),
            //    TempData = null
            //};

            //return viewResult;
            return new EmptyResult();
        }
        public CustomControllerFactory()
        {
            var aggregateCatalog = new AggregateCatalog();
            var config = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/PluginConfig.xml"));
            if (config.Root != null)
            {
                var paths = (from path in config.Root.Elements("PluginName") select path).AsEnumerable();
                foreach (var path in paths)
                {
                    aggregateCatalog.Catalogs.Add(
                        new DirectoryCatalog(Path.Combine(HttpContext.Current.Server.MapPath("~/Plugin"), path.Value)));
                }
            }
            aggregateCatalog.Catalogs.Add(new DirectoryCatalog(HttpContext.Current.Server.MapPath("~/bin")));
            _container = new CompositionContainer(aggregateCatalog,
                CompositionOptions.DisableSilentRejection | CompositionOptions.IsThreadSafe);

            DefaultControllerFactory = new DefaultControllerFactory();
        }
Пример #15
0
        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            if (controllerName.ToLower().StartsWith("projects"))
            {
                ProjectsRepository rep = new ProjectsRepository();
                var controller = new ProjectsController(rep);
                return controller;
            }
            var defaultController = new DefaultControllerFactory();
            try
            {
                IController controllerFound = defaultController.CreateController(requestContext, controllerName);
                return controllerFound;
            }
            catch (Exception ex)
            {
                Log.write(ex.Message, "ERR");
            }

            return new HomeController();
        }
        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            //get spring context
            WebApplicationContext ctx = ContextRegistry.GetContext() as WebApplicationContext;
            string controller = "Clover.Web.Controllers." + controllerName + "Controller";
            //查找是否配置该Controller
            if (ctx.ContainsObject(controller))
            {
                object controllerf = ctx.GetObject(controller);
                return (IController)controllerf;

            }
            else
            {
                if (defalutf == null)
                {
                    defalutf = new DefaultControllerFactory();
                }

                return defalutf.CreateController(requestContext, controllerName);
            }
        }
Пример #17
0
        protected void Application_Error(object sender, EventArgs e)
        {
            try
            {
                //Log the error in log file and in database
                var exception = Server.GetLastError();
                Response.Clear();

                var rqstContext = Request.RequestContext;
                rqstContext.RouteData.Values["action"] = "ApplicationError";
                rqstContext.RouteData.Values["ex"] = exception;
                rqstContext.RouteData.Values["controller"] = "Error";

                var controllerFactory = new DefaultControllerFactory();
                var errorController = controllerFactory.CreateController(rqstContext, "Error");
                errorController.Execute(rqstContext);

                Server.ClearError();
            }
            catch (Exception ex)
            {
                //Igone error here to avoid infinte looping
            }
        }
        public void GetControllerSessionBehaviorReturnsDefaultForNullControllerType() {
            // Arrange
            var factory = new DefaultControllerFactory();

            // Act
            SessionStateBehavior result = factory.GetControllerSessionBehavior(null, null);

            // Assert
            Assert.AreEqual(SessionStateBehavior.Default, result);
        }
        public MefControllerFactory(string pluginPath)
        {
            this.pluginPath = pluginPath;

            this.defaultControllerFactory = new DefaultControllerFactory();
        }
        public void ActivatorResolverAndDependencyResolverAreNeverCalledWhenControllerActivatorIsPassedInConstructor() {
            // Arrange
            var context = new RequestContext();
            var expectedController = new Goodcontroller();

            Mock<IControllerActivator> activator = new Mock<IControllerActivator>();
            activator.Setup(a => a.Create(context, typeof(Goodcontroller))).Returns(expectedController);

            var resolverActivator = new Mock<IControllerActivator>(MockBehavior.Strict);
            var activatorResolver = new Resolver<IControllerActivator> { Current = resolverActivator.Object };

            var dependencyResolver = new Mock<IDependencyResolver>(MockBehavior.Strict);

            //Act
            var factory = new DefaultControllerFactory(activator.Object, activatorResolver, dependencyResolver.Object);
            IController returnedController = factory.GetControllerInstance(context, typeof(Goodcontroller));

            //Assert
            Assert.AreSame(returnedController, expectedController);
        }
        public void GetControllerDelegatesToDependencyResolveWhenActivatorResolverIsNull() {
            // Arrange
            var context = new RequestContext();
            var expectedController = new Goodcontroller();
            var dependencyResolver = new Mock<IDependencyResolver>(MockBehavior.Strict);
            dependencyResolver.Setup(dr => dr.GetService(typeof(Goodcontroller))).Returns(expectedController);
            var factory = new DefaultControllerFactory(null, null, dependencyResolver.Object);

            // Act
            IController returnedController = factory.GetControllerInstance(context, typeof(Goodcontroller));

            // Assert
            Assert.AreSame(returnedController, expectedController);
        }
        public void GetControllerDelegatesToActivatorCreateInstanceWhenDependencyResolverReturnsNull() {
            // Arrange
            var context = new RequestContext();
            var dependencyResolver = new Mock<IDependencyResolver>();
            var factory = new DefaultControllerFactory(null, null, dependencyResolver.Object);

            // Act & Assert
            ExceptionHelper.ExpectInvalidOperationException(
                () => factory.GetControllerInstance(context, typeof(NoParameterlessCtor)),
                "An error occurred when trying to create a controller of type 'System.Web.Mvc.Test.DefaultControllerFactoryTest+NoParameterlessCtor'. Make sure that the controller has a parameterless public constructor."
            );
        }
Пример #23
0
        /// <summary>
        ///     Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            IEnumerable<IRegister> registers = AssemblyManager.GetTypeInstances<IRegister>();

            if (registers != null && registers.Any())
                foreach (IRegister register in registers)
                {
                    register.Kernel = kernel;
                    register.Register();
                }

            //Jsonp Support
            GlobalConfiguration.Configuration.Formatters.Insert(0, new JsonpMediaTypeFormatter());

            //for web api
            GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel);

            //for mvc controllers
            var controllerActivator = new NinjectControllerActivator(kernel);
            var controllerFactory = new DefaultControllerFactory(controllerActivator);
            ControllerBuilder.Current.SetControllerFactory(controllerFactory);


        }
        public void GetControllerDelegatesToActivatorResolver() {
            //Arrange
            var context = new RequestContext();
            var expectedController = new Goodcontroller();
            var resolverActivator = new Mock<IControllerActivator>();
            resolverActivator.Setup(a => a.Create(context, typeof(Goodcontroller))).Returns(expectedController);
            var activatorResolver = new Resolver<IControllerActivator> { Current = resolverActivator.Object };
            var factory = new DefaultControllerFactory(null, activatorResolver, null);

            //Act
            IController returnedController = factory.GetControllerInstance(context, typeof(Goodcontroller));

            //Assert
            Assert.AreSame(returnedController, expectedController);
        }
        public void GetControllerTypeForNoAssemblies() {
            // Arrange
            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());
            DefaultControllerFactory factory = new DefaultControllerFactory();
            MockBuildManager buildManagerMock = new MockBuildManager(new Assembly[] { });
            ControllerTypeCache controllerTypeCache = new ControllerTypeCache();

            factory.BuildManager = buildManagerMock;
            factory.ControllerTypeCache = controllerTypeCache;

            // Act
            Type controllerType = factory.GetControllerType(requestContext, "sometype");

            // Assert
            Assert.IsNull(controllerType, "Shouldn't have found a controller type.");
            Assert.AreEqual<int>(0, controllerTypeCache.Count, "Cache should be empty.");
        }
        public void GetControllerInstanceConsultsSetControllerActivator() {
            //Arrange
            Mock<IControllerActivator> activator = new Mock<IControllerActivator>();
            DefaultControllerFactory factory = new DefaultControllerFactory(activator.Object);
            RequestContext context = new RequestContext();

            //Act
            factory.GetControllerInstance(context, typeof(Goodcontroller));

            //Assert
            activator.Verify(l => l.Create(context, typeof(Goodcontroller)));
        }
        public void GetControllerSessionBehaviorReturnsAttributeValueFromController() {
            // Arrange
            var factory = new DefaultControllerFactory();

            // Act
            SessionStateBehavior result = factory.GetControllerSessionBehavior(null, typeof(MyReadOnlyController));

            // Assert
            Assert.AreEqual(SessionStateBehavior.ReadOnly, result);
        }
        public void GetControllerSessionBehaviorReturnsDefaultForControllerWithoutAttribute() {
            // Arrange
            var factory = new DefaultControllerFactory();

            // Act
            SessionStateBehavior result = factory.GetControllerSessionBehavior(null, typeof(object));

            // Assert
            Assert.AreEqual(SessionStateBehavior.Default, result);
        }
Пример #29
0
        public ControllerFactory()
        {
            defaultFactory = new DefaultControllerFactory();

            iocFactory = Factory.GetInst();
        }
        public void GetControllerSessionBehaviorGuardClauses() {
            // Arrange
            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());
            IControllerFactory factory = new DefaultControllerFactory();

            // Act & Assert
            ExceptionHelper.ExpectArgumentNullException(
                () => factory.GetControllerSessionBehavior(null, "controllerName"),
                "requestContext"
            );
            ExceptionHelper.ExpectArgumentExceptionNullOrEmpty(
                () => factory.GetControllerSessionBehavior(requestContext, null),
                "controllerName"
            );
            ExceptionHelper.ExpectArgumentExceptionNullOrEmpty(
                () => factory.GetControllerSessionBehavior(requestContext, ""),
                "controllerName"
            );
        }
        public void GetControllerInstanceThrowsIfControllerTypeIsNotControllerBase() {
            // Arrange
            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());
            DefaultControllerFactory factory = new DefaultControllerFactory();

            // Act
            ExceptionHelper.ExpectArgumentException(
                delegate {
                    factory.GetControllerInstance(requestContext, typeof(int));
                },
                "The controller type 'System.Int32' must implement IController.\r\nParameter name: controllerType");
        }