2009-09-18 78 views
2

我有一个应用程序,仿照从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

+0

你最后的结论是什么?我有同样的设计问题。 – Jon 2011-01-14 12:46:00

+0

看了这个之后不久,我在应用程序中发现了一处内存泄漏,它来自Castle Windsor代码中的某个地方(无论是我使用它的方式是否正确,我不知道,但是我是在使用它简单的水平,所以我不是100%确定它_was_我),所以我没有得到解决这些解决方案 - 对不起。如果你尝试下面的解决方案,它的工作原理,请让我知道,我会标记为正确的。 – 2011-01-18 09:39:31

回答

1

获取(以及更多),它不`吨工作了王氏windor城堡的最后一个版本,其实,微内核装配在城堡内部融化.Core

+0

你的黄花鱼内尔在城堡里面融化了吗?听起来像一个特洛伊木马,我的意思是青蛙。 – 2013-12-24 23:13:40

5

刚刚宣布在你的控制器构造您需要的依赖,即:

public class MyController: Controller { 
    private readonly IItemsRepository itemsRepo; 
    private readonly IPersonRepository personRepo; 
    public MyController(IItemsRepository i, IPersonRepository p) { 
    itemsRepo = i; 
    personRepo = p; 
    } 
} 

温莎会自动解决依赖性,当它实例化控制器。

有很多关于谷歌代码的项目可以用于指导,例如WineCellarManager

BTW:你不需要编写自己的WindsorControllerFactory,你可以从MVCContrib

+0

这并不总是实用的,例如在对象验证规则中,我需要检查针对主DB添加的任何零件编号 - 最好在对象中执行此操作,因为它使业务逻辑远离控制器,但对象不会没有回购(我也不是真的想创建一个,除非我需要检查数据) – 2009-09-24 11:32:42

+0

验证与此无关......请为此创建另一个问题 – 2009-09-24 12:10:47

+0

它的确如此,因为在我的验证规则中,我需要访问数据库回购。 – 2009-09-24 13:20:04