ASP.. NET MVC 6控制器工厂

本文关键字:控制器 工厂 MVC NET ASP | 更新日期: 2023-09-27 18:02:40

我想从数据库(ASP. net)创建控制器的动作。. NET MVC 6 vNext)。我有表控制器和动作action表的属性为"{ ViewPath, ActionName }",其中"actionName"为"{Controller}/{ActionName}"我想建立这样的页面。我怎样才能做到呢?我有MVC 4类,但我需要重写为MVC 6

public class ITSDefaultController : DefaultControllerFactory
    {
        public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            try
            {
                return base.CreateController(requestContext, controllerName) as Controller;
            }
            catch (Exception)
            {
                Controller controller = new ITSControllerBase();
                using (var db = new ITS.Database.DatabaseDataContext())
                {
                    string action = requestContext.RouteData.Values["action"] as string;
                    DynamicAction dynamicAction = null;
                    if (!db.Controllers.Any(x => x.ControllerName == controllerName && x.Views.Any(v => v.ViewName == action)))
                    {
                        dynamicAction = Actions["NotFound"].First();
                        requestContext.RouteData.Values["controller"] = "NotFound";
                        requestContext.RouteData.Values["action"] = "Index";
                    }
                    else
                    {
                        dynamicAction = new DynamicAction()
                        {
                            ActionName = db.Views.First(d => d.ViewName == action && d.Controller.ControllerName == controllerName).ViewName,
                            Result = () => new ViewResult()
                        };
                    }

                    if (dynamicAction != null)
                    {
                        controller.ActionInvoker = new DynamicActionInvoker() { DynamicAction = dynamicAction };
                    }
                    return controller;
                }
            }
        }
        public override void ReleaseController(IController controller)
        {
            base.ReleaseController(controller);
        }
        public static ConcurrentDictionary> Actions = new ConcurrentDictionary>();
    }

ASP.. NET MVC 6控制器工厂

实际上我有同样的需要替换Mvc管道组件的一些自定义的,我发现IControllerFactory和IControllerActivator及其默认实现仍然是相同的,然后的经验是用CustomControllerFactory取代Mvc 6 DefaultControllerFactory,我已经做了一些测试在ConfigureServices上的启动类:

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddMvc();
       var serviceDescriptor = services.FirstOrDefault(s => s.ServiceType.FullName.Contains("IControllerFactory"));
       var serviceIndex = services.IndexOf(serviceDescriptor);
       services.Insert(serviceIndex, new ServiceDescriptor(typeof(IControllerFactory), typeof(CustomControllerFactory), ServiceLifeTime.Singleton));
       services.RemoveAt(serviceIndex + 1);
    }

就完成了,您还可以向IServiceCollection接口添加一个扩展方法:

    public static class ServiceCollectionExtensions
    {
        public static void(this IServiceCollection services, Type serviceType, Type implementationType, ServiceLifetime serviceLifetime = ServiceLifetime.Singleton)
        {
            var serviceDescriptor = services.FirstOrDefault(s => s.ServiceType == serviceType);
            var serviceIndex = services.IndexOf(serviceDescriptor);
            services.Insert(serviceIndex, new ServiceDescriptor(serviceType, implementationType, serviceLifetime));
            services.RemoveAt(serviceIndex + 1);
        }
    }
修改后的

可以像这样简单地使用:

    ......
    services.AddMvc();
    services.ReplaceService(typeof(IControllerActivator), typeof(CustomControllerActivator));
    services.ReplaceService(typeof(IControllerFactory), typeof(CustomControllerFactory));
    ......

,然后你可以替换Mvc 6管道上的任何组件;

     public class HomeController : Controller
        {
            public string _MyName { get; set; }
            // GET: Home
            public ActionResult Index()
            {
                return Content(_MyName);
            }
            public HomeController(string Name)
            {
                _MyName = Name;
            }
        }

 public class MyCustomController : IControllerFactory
    {
        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            HomeController objHomeController = new HomeController("Any thing Which you want to pass/inject.");
            return objHomeController;
        }
        public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
        {
            return SessionStateBehavior.Default;
        }
        public void ReleaseController(IController controller)
        {
            IDisposable disposable = controller as IDisposable;
            if(disposable!=null)
            {
                disposable.Dispose();
            }
        }
    }

 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            ControllerBuilder.Current.SetControllerFactory(new MyCustomController());
        }