通过注册允许容器解析控制器的控制器工厂,您可以使用IoC容器为您解析映射 - 容器将解析控制器类型并注入接口的具体实例。
例在MvcApplication
类使用Castle Windsor
在Global.asax中
:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ControllerBuilder.Current.SetControllerFactory(new WindsorControllerFactory());
}
WindsorControllerFactory
类
using System;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Core.Resource;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
public class WindsorControllerFactory : DefaultControllerFactory
{
WindsorContainer container;
public WindsorControllerFactory()
{
container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (Type t in controllerTypes)
container.AddComponentWithLifestyle(t.FullName, t, Castle.Core.LifestyleType.Transient);
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
// see http://stackoverflow.com/questions/1357485/asp-net-mvc2-preview-1-are-there-any-breaking-changes/1601706#1601706
if (controllerType == null) { return null; }
return (IController)container.Resolve(controllerType);
}
}
羞于承认我从来没有听说过的IoC容器。我从来没有碰过依赖注入。你能给我一个解释和例子,说明它的使用方法吗? – GenericTypeTea 2010-05-08 20:48:39
控制反转(IoC)通过管理类型之间的依赖来帮助构建松散耦合的系统 - 很多时候对象可以依赖于其他对象,例如,控制器依赖于存储库来填充模型。这些依赖关系可以使用IoC容器进行管理,以便当某个类型需要另一个类型的实例时,它会向容器请求它,并且该容器将返回它被配置为返回的类型的实例... – 2010-05-08 21:08:38
例如,您的控制器想要一个'ICustomerRepository'的具体实例,所以它要求它的容器。尽管我们可以进一步推进,但我们也可以让容器管理控制器的实例化。我们在这里获得的好处以及使用IoC容器的众多原因之一是,在实例化控制器时,容器会意识到它具有对“ICustomerRepository”的依赖并实例化它(也称为依赖注入) 。 – 2010-05-08 21:12:47