这种方式是利用ControllerFactory来实现的。
首先我们要自定义自己的ControllerFactory :
public class MEFControllerFactory : DefaultControllerFactory
{
private CompositionContainer Container;
public MEFControllerFactory()
{
var catalog = new AggregateCatalog(new DirectoryCatalog(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath));
Container = new CompositionContainer(catalog);
}
protected override IController GetControllerInstance(RequestContext reqContext,
Type controllerType)
{
return Container.GetExportedValue<IController>();
}
}
{
private CompositionContainer Container;
public MEFControllerFactory()
{
var catalog = new AggregateCatalog(new DirectoryCatalog(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath));
Container = new CompositionContainer(catalog);
}
protected override IController GetControllerInstance(RequestContext reqContext,
Type controllerType)
{
return Container.GetExportedValue<IController>();
}
}
然后我们在Global.asax.cs里的Application_Start()是注册我们自定义的ControllerFactory:
protected void Application_Start()
{
MEFControllerFactory controllerFactory = new MEFControllerFactory();
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
{
MEFControllerFactory controllerFactory = new MEFControllerFactory();
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
基本的工作已经做完了。然后我们就可以按照MEF的方式进行注入了。但是需要注意一点我们的Controller类上面一定要加[PartCreationPolicy(CreationPolicy.NonShared)],因为web多线程调用的原因。Controller最好这样注入[Export(typeof(IController))]。
当然也可以利用DependencyResolver来实现。