【发布时间】:2009-09-18 16:56:01
【问题描述】:
我有一个应用程序,以 Apress Pro ASP.NET MVC 的应用程序为模型,它使用 Castle Windsor 的 IoC 来实例化控制器及其各自的存储库,并且运行良好
例如
public class ItemController : Controller
{
private IItemsRepository itemsRepository;
public ItemController(IItemsRepository windsorItemsRepository)
{
this.itemsRepository = windsorItemsRepository;
}
与
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Castle.Windsor;
using Castle.Windsor.Configuration.Interpreters;
using Castle.Core.Resource;
using System.Reflection;
using Castle.Core;
namespace WebUI
{
public class WindsorControllerFactory : DefaultControllerFactory
{
WindsorContainer container;
// The constructor:
// 1. Sets up a new IoC container
// 2. Registers all components specified in web.config
// 3. Registers all controller types as components
public WindsorControllerFactory()
{
// Instantiate a container, taking configuration from web.config
container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
// Also register all the controller types as transient
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, LifestyleType.Transient);
}
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
}
}
控制控制器的创建。
我有时需要在控制器中创建其他存储库实例,以从其他地方获取数据,我可以使用 CW IoC 执行此操作吗?如果可以,那么如何操作?
我一直在尝试创建新的控制器类,因为它们应该使用我现有的代码自动注册(如果我可以让它工作,我可以稍后正确注册它们)但是当我尝试实例化它们时一个明显的反对意见,因为我不能为构造函数提供一个 repos 类(我很确定这是错误的方法)。
任何帮助(尤其是示例)将不胜感激。 干杯 MH
【问题讨论】:
-
你最后的结论是什么。我有同样的设计问题。
-
看到这个后不久,我发现应用程序中存在内存泄漏,这来自 Castle Windsor 代码中的某个地方(是否是我使用不正确,我不知道,但我只是在一个简单的级别上使用它,所以我不能 100% 确定它是我)所以我没有去检查这些解决方案 - 抱歉。如果您尝试以下解决方案并且有效,请告诉我,我会将其标记为正确。
标签: inversion-of-control castle-windsor