使用Spring .NET将依赖注入MVC​​控制器

时间:2012-09-05 18:19:06

标签: c# .net 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>

。 。

<!-- Spring Context Configuration -->
<spring>
    <context>
        <resource uri="config://spring/objects"/>
    </context>
    <objects configSource="App_Config\Spring.config" />
</spring>
<!-- End Spring Context Configuration -->

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>

的TestController:

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

问题:

  

在运行时,ObjectA不会被注入并保持为null   在整个代码中导致null异常。

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

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

2 个答案:

答案 0 :(得分:3)

事实证明,我错过了Spring for MVC的一个非常重要的部分。

我对此问题的解决方案是添加一个实现IDependencyResolver的DependencyResolver。

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()));
    }

答案 1 :(得分:1)

您可以像在答案中建议的那样实施自己的IDependencyResolver。请注意,因为(iirc)版本1.3.1 Spring.NET内置支持asp.net mvc 2.03.0。 Spring.net 2.0(pre release available on NuGet)也内置了对4.0版的支持。请考虑使用这些库。

您可能有兴趣将SpringDependencyResolverthe one provided by the Spring.net team进行比较。