我有一个应用程序,仿照从Apress的临ASP.NET MVC使用温莎城堡的IoC实例有各自的资料库控制器的一个,这是工作的罚款ASP.NET MVC使用温莎城堡的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
你最后的结论是什么?我有同样的设计问题。 – Jon 2011-01-14 12:46:00
看了这个之后不久,我在应用程序中发现了一处内存泄漏,它来自Castle Windsor代码中的某个地方(无论是我使用它的方式是否正确,我不知道,但是我是在使用它简单的水平,所以我不是100%确定它_was_我),所以我没有得到解决这些解决方案 - 对不起。如果你尝试下面的解决方案,它的工作原理,请让我知道,我会标记为正确的。 – 2011-01-18 09:39:31