【问题标题】:Inject object with "request" scope into prototype object将具有“请求”范围的对象注入原型对象
【发布时间】:2011-06-12 17:08:47
【问题描述】:

我在我的 Asp.Net MVC 应用程序中使用 Spring.Net,其中控制器必须定义为原型(非单例)。我有必须具有请求范围的对象(每个请求的新对象)。有没有办法将它们注入我的控制器?

  <object type="xx.CompanyController, xx" singleton="false">
    <property name="Service" ref="ServiceA" />
  </object>

  <object id="ServiceA" type="xx.ServiceA, xx" scope="request"/>    
    <property name="ObjectB" ref="ObjectB" />
  </object>

  <object id="ObjectB" type="xx.ObjectB, xx" scope="request"/>

像这样,除了控制器之外的所有对象都被视为单例。 ObjectB 不能是原型,因为它被一些需要共享相同实例的其他对象引用。从控制器中删除 singleton="false" 并添加 scope="request" 也不起作用(控制器被视为单例)。

我使用 Spring.Net 1.3.1 和 MvcApplicationContext

【问题讨论】:

  • 我注意到了同样的行为。也就是说,如果对象是 singleton 对象的依赖项,则使用 request 范围定义的对象将被“提升”为单例范围。

标签: c# .net asp.net-mvc asp.net-mvc-2 spring.net


【解决方案1】:

您应该使用自己的设置 ControllerFactory。

protected void Application_Start()
{
//...
    ControllerBuilder.Current.SetControllerFactory(new IoCControllerFactory());
//...
}

IoCControllerFactory 必须继承自 DefaultControllerFactory

public class IoCControllerFactory : DefaultControllerFactory

并覆盖 GetControllerInstance

protected override IController GetControllerInstance (RequestContext requestContext, Type controllerType)
    {
        ObjectTypeUtility.ArgumentIsNull(controllerType, "controllerType", true);
         if (!typeof(IController).IsAssignableFrom(controllerType))
             throw new ArgumentException(string.Format(
                       "Type requested is not a controller: {0}",
                       controllerType.Name), 
                        "controllerType");    

            IController controller = IoCWorker.Resolve(controllerType) 
                                      as IController;                
            return controller;

    }

IoCWorker 是一个具有 Resolve 注入方法的类,我正在使用 Unity,我无法提供 IoCWorker 实现-如果您需要我可以分享-。

它将为您的控制器工作 ctor injection。

祝你好运。

【讨论】:

  • 问题不在于 asp.net MVC 中的 IoC 是否可行(我已经在 Spring.Net 中使用它),而在于 (Spring-) 对象定义的不同 (Spring-) 范围。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 2023-03-14
  • 1970-01-01
相关资源
最近更新 更多