简体   繁体   中英

How to integrate WebApi 2 with Spring.Net

Im trying to integrate WebApi 2 with Spring.Net with not success. This is what i have tried:

public class MvcApplication : SpringMvcApplication
{
    protected void Application_Start()
    {
        XmlConfigurator.Configure();

        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

When is creating the SpringWebApiDependencyResolver instance, i'm getting this exception:

Error creating context 'spring.root': Request is not available in this context

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.DependencyResolver = new SpringWebApiDependencyResolver(ContextRegistry.GetContext());

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Im using Spring.Net 2.0.1

Now is working, the following line was not needed:

config.DependencyResolver = new SpringWebApiDependencyResolver(ContextRegistry.GetContext());

This is my implementation based on Spring.Net example :

public class MvcApplication : SpringMvcApplication
{
    protected void Application_Start()
    {
        // More config...
        GlobalConfiguration.Configure(WebApiConfig.Register);
        // More config...
    }

    protected override System.Web.Http.Dependencies.IDependencyResolver BuildWebApiDependencyResolver()
    {
        var resolver = base.BuildWebApiDependencyResolver();

        var springResolver = resolver as SpringWebApiDependencyResolver;

        if (springResolver != null)
        {
            var resource = new AssemblyResource(
                "assembly://assemblyName/namespace/ChildControllers.xml");
            springResolver.AddChildApplicationContextConfigurationResource(resource);
        }

        return resolver;
    }
}

I prefered to keep the common WebApi configuration:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

For registration of controllers in the IoC container is the same as MVC integration:

<object type="namespace.PrefixController, assemblyName" singleton="false" >
    <property name="Dependency1" ref="Dependency1" />
</object>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM