【发布时间】:2011-02-26 15:57:30
【问题描述】:
我正在阅读 Sanderson 的 Pro ASP.NET MVC 框架,在第 4 章中他讨论了Creating a Custom Controller Factory,看来用于注册控制器的原始方法AddComponentLifeStyle 或AddComponentWithLifeStyle 现在已弃用:
public class WindsorControllerFactory : DefaultControllerFactory
{
IWindsorContainer container;
public WindsorControllerFactory()
{
container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
// register all the controller types as transient
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
//[Obsolete("Use Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)) instead.")]
//IWindsorContainer AddComponentLifeStyle<I, T>(string key, LifestyleType lifestyle) where T : class;
foreach (Type t in controllerTypes)
{
container.Register(Component.For<IController>().ImplementedBy<???>().Named(t.FullName).LifeStyle.Is(LifestyleType.Transient));
}
}
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
}
新建议是使用Register(Component.For<I>().ImplementedBy<T>().Named(key).Lifestyle.Is(lifestyle)),但我不知道如何在ImplementedBy<???>() 方法中呈现实现控制器类型。我试过ImplementedBy<t>() 和ImplementedBy<typeof(t)>(),但是我找不到合适的方法来传入实现类型。有什么想法吗?
【问题讨论】:
-
请不要将桑德斯的书用于与温莎有关的任何内容,它现在非常已经过时了。
-
@Mauricio Schaffer,我意识到有些东西已经过时了,但是有一些漂亮的宝石可能有用......特别是使用 Web.config 来帮助解决依赖关系:例如提供初始化存储库类所需的连接字符串(尽管我还没有弄清楚如何去做)。
-
那也过时了,我不建议这样做。
-
@Mauricio,可能没有解决依赖关系,但至少使用连接字符串或数据库名称(在我的另一个问题的示例中)。
标签: asp.net-mvc reflection inversion-of-control castle-windsor