預設 MVC 專案將 Controller 放在主專案,隨專案增大需拆分為獨立類別庫 (DLL) 以利團隊開發、多專案共用、單元測試。本文示範兩種實作方式。
實作 `IControllerFactory` 介面,三個核心方法:`CreateController`、`GetControllerSessionBehavior`、`ReleaseController`。
using System;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.SessionState;
namespace BookSystem_Controllers
{
public class ControllersFactory : IControllerFactory
{
private readonly string _assemblyName;
private readonly string _defaultNamespace;
private Assembly _controllerAssembly;
public ControllersFactory(string assemblyName, string defaultNamespace = null)
{
_assemblyName = assemblyName;
_defaultNamespace = defaultNamespace;
}
public Assembly ControllerAssembly
=> _controllerAssembly ?? (_controllerAssembly = Assembly.Load(_assemblyName));
public string GetControllerFullName(string controllerName)
{
var ns = String.IsNullOrEmpty(_defaultNamespace) ? _assemblyName : _defaultNamespace;
return $"{ns}.{controllerName}Controller";
}
public IController CreateController(RequestContext requestContext, string controllerName)
{
var typeName = GetControllerFullName(controllerName);
var controllerType = ControllerAssembly.GetType(typeName);
if (controllerType == null) return null;
var controller = Activator.CreateInstance(controllerType) as Controller;
if (controller == null) return null;
controller.ControllerContext = new ControllerContext(requestContext, controller);
return controller;
}
public SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, string controllerName)
{
return SessionStateBehavior.Default;
}
public void ReleaseController(IController controller)
{
var disposable = controller as IDisposable;
disposable?.Dispose();
}
}
}
public static void RegisterRoutes(RouteCollection routes)
{
// 必須在 MapRoute 之前註冊
ControllerBuilder.Current.SetControllerFactory(
new ControllersFactory("BookSystem_Controllers", "BookSystem_Controllers.Controllers")
);
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
不需自訂 Factory,直接在 `MapRoute` 指定 `namespaces` 參數:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "BookSystem_Controllers.Controllers" } // 指定 Controller 命名空間
);
Solution/
├── BookSystem.Web/ # MVC 主專案 (Views, wwwroot, Global.asax)
├── BookSystem.Controllers/ # Controller 類別庫 (參考 System.Web.Mvc)
├── BookSystem.Services/ # Business Logic
├── BookSystem.Data/ # Repository, EF Context
└── BookSystem.Common/ # DTO, Extension, Helper
現代替代: ASP.NET Core 原生支援 `ApplicationPart` 自動發現外部組件 Controller,無需自訂 Factory,只需 `AddControllers().AddApplicationPart(typeof(ExternalController).Assembly)` 即可。