gpt4 book ai didi

c# - 使用 Spring .NET 将依赖项注入(inject) MVC Controller

转载 作者:太空狗 更新时间:2023-10-29 23:24:52 26 4
gpt4 key购买 nike

Controller 中的对象未在运行时注入(inject)。

网络配置:

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

Spring 配置:

<?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>

测试 Controller :

public class TestController: Controller
{
// this object will be injected by Spring.net at run time
private ClassA ObjectA { get; set; }

问题:

At runtime the ObjectA does not get injected and stays null, which cause null exception throughout the code.

备选方案:我可以使用以下代码手动初始化 Spring 对象并获取它的对象。

        var ctx = ContextRegistry.GetContext();
var objectA = ((IObjectFactory)ctx).GetObject("ObjectImpl") as ClassA;

最佳答案

事实证明我遗漏了 MVC 的 Spring 实现的一个非常重要的部分。

我的解决方案是添加一个实现 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>();
}
}

Global.asax.cs:

    protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);

DependencyResolver.SetResolver(new SpringDependencyResolver(ContextRegistry.GetContext()));
}

关于c# - 使用 Spring .NET 将依赖项注入(inject) MVC Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12287472/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com