c# - 将范围为 "request"的对象注入(inject)原型(prototype)对象

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

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

  <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"/>

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

我使用 Spring.Net 1.3.1 和 MvcApplicationContext

最佳答案

您应该使用您自己的设置 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 注入(inject)方法的类,我正在使用 Unity,我无法提供 IoCWorker 实现 - 如果您需要,我可以分享-。

它将为您的 Controller 工作。

祝你好运。

关于c# - 将范围为 "request"的对象注入(inject)原型(prototype)对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4751788/

相关文章:

c# - 根据公钥指数/模数进行 WinRT RSA 加密

c# - 使用 C# 获取网络摄像头状态

c# - TimeZoneInfo 和夏令时

asp.net-mvc - MVC 4自定义验证属性在服务器端触发两次

asp.net-mvc - TDD 与 ASP.NET MVC 1.0

c# - ASP.NET 中的 Console.WriteLine

c# - 处理后是否有可能获得 Timer.Tick 事件

c# - OwnerDrawText模式下TreeView节点文本的定位和高亮

c# - 第二次调用同一个 DbContext 导致错误 'DbContext has been disposed'

asp.net-mvc - 是否可以通过单击按钮获得 'Swap' 部分 View ?