控制器中的对象在运行时没有被注入。
网络配置:
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
. . .
<!-- Spring Context Configuration -->
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects configSource="App_Config\Spring.config" />
</spring>
<!-- End Spring Context Configuration -->
弹簧配置:
<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
<!-- Crest is the WCF service to be exposed to the client, could not use a singleton -->
<object id="TestController" type="Project.Controllers.TestController, Project" singleton="false">
<property name="ObjectA" ref="ObjectImpl"/>
</object>
<object id="ObjectImpl" type="Project.Code.Implementations.ClassA, Project" singleton="false" />
</objects>
测试控制器:
public class TestController: Controller
{
// this object will be injected by Spring.net at run time
private ClassA ObjectA { get; set; }
问题:
在运行时,ObjectA 不会被注入并保持为空,这会导致整个代码出现空异常。
替代方案:我可以手动初始化 Spring 对象并使用以下代码获取它的对象。
var ctx = ContextRegistry.GetContext();
var objectA = ((IObjectFactory)ctx).GetObject("ObjectImpl") as ClassA;