我想使用插件架构(MEF)重构我的MVC项目,并且我在开始时就开始了。 我通过
获得全球授权filters.Add(new System.Web.Mvc.AuthorizeAttribute());
一些控制器应该是公共的,之前我只使用了属性[AllowAnonymous]。现在我将一些控制器移动到单独的插件中,它们看起来像这样:
[Export("LinkedDocument", typeof(IController))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class LinkedDocumentController : Controller
{
[HttpGet]
[AllowAnonymous]
public ActionResult Index()
{
//...
}
}
现在,当我请求我的页面时,我被重定向到我的登录页面,这是不打算的。如果我在我的网站上授权它工作正常,所以我想我会错过一些配置左右。这是我第一次在我的项目中使用MEF。
我的Application_Start是:
protected void Application_Start()
{
var pluginFolders = new List<string>();
var plugins = Directory.GetDirectories(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Modules")).ToList();
plugins.ForEach(s =>
{
var di = new DirectoryInfo(s);
pluginFolders.Add(di.Name);
});
AreaRegistration.RegisterAllAreas();
//Loads assemblies
Bootstrapper.Compose(pluginFolders);
WebApiConfig.Register(GlobalConfiguration.Configuration);
//ControllerFactory get's aproppriate controler
ControllerBuilder.Current.SetControllerFactory(new MefControllerFactory());
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ViewEngines.Engines.Add(new MefViewEngine(pluginFolders));
}
Bootstrapper使用控制器加载程序集。它的代码是:
public class Bootstrapper
{
//..
public static T GetInstance<T>(string contractName = null)
{
var type = default(T);
if (CompositionContainer == null) return type;
if (!string.IsNullOrWhiteSpace(contractName))
type = CompositionContainer.GetExportedValue<T>(contractName);
else
type = CompositionContainer.GetExportedValue<T>();
return type;
}
public static void Compose(List<string> pluginFolders)
{
//..
}
}
最后,MefControllerFactory是:
public class MefControllerFactory : IControllerFactory
{
//..
public IController CreateController(RequestContext requestContext, string controllerName)
{
var controller = Bootstrapper.GetInstance<IController>(controllerName);
if (controller == null)
throw new Exception("Controller not found!");
return controller;
}
}
请注意,有些控制器包含需要授权的操作和不需要的操作。