我在我的 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/