Jun*_*eng 5 .net c# asp.net-mvc dependency-injection spring.net
控制器中的对象不会在运行时注入.
Web.config文件:
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core" />
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
Run Code Online (Sandbox Code Playgroud)
...
<!-- Spring Context Configuration -->
<spring>
<context>
<resource uri="config://spring/objects"/>
</context>
<objects configSource="App_Config\Spring.config" />
</spring>
<!-- End Spring Context Configuration -->
Run Code Online (Sandbox Code Playgroud)
Spring.config:
<?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>
Run Code Online (Sandbox Code Playgroud)
的TestController:
public class TestController: Controller
{
// this object will be injected by Spring.net at run time
private ClassA ObjectA { get; set; }
Run Code Online (Sandbox Code Playgroud)
问题:
在运行时,ObjectA不会被注入并保持为null,这会在整个代码中导致null异常.
替代方案:我可以使用以下代码手动初始化Spring对象并获取它的对象.
var ctx = ContextRegistry.GetContext();
var objectA = ((IObjectFactory)ctx).GetObject("ObjectImpl") as ClassA;
Run Code Online (Sandbox Code Playgroud)
事实证明我错过了 Spring MVC 实现的一个非常重要的部分。
我对这个问题的解决方案是添加一个实现 IDependencyResolver 的 DependencyResolver 。
依赖解析器:
public class SpringDependencyResolver : IDependencyResolver
{
private readonly IApplicationContext _context;
public SpringDependencyResolver(IApplicationContext context)
{
_context = context;
}
public object GetService(Type serviceType)
{
var dictionary = _context.GetObjectsOfType(serviceType).GetEnumerator();
dictionary.MoveNext();
try
{
return dictionary.Value;
}
catch (InvalidOperationException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _context.GetObjectsOfType(serviceType).Cast<object>();
}
}
Run Code Online (Sandbox Code Playgroud)
Global.asax.cs:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
DependencyResolver.SetResolver(new SpringDependencyResolver(ContextRegistry.GetContext()));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4162 次 |
| 最近记录: |