gpt4 book ai didi

c# - 如何将 WebApi 2 与 Spring.Net 集成

转载 作者:行者123 更新时间:2023-11-30 20:44:00 25 4
gpt4 key购买 nike

我尝试将 WebApi 2Spring.Net 集成,但没有成功。这是我尝试过的:

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

在创建 SpringWebApiDependencyResolver 实例时,出现以下异常:

创建上下文“spring.root”时出错:请求在此上下文中不可用

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

我正在使用 Spring.Net 2.0.1

最佳答案

现在可以正常工作了,不需要下面这行:

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

这是我基于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;
}
}

我更喜欢保留常见的 WebApi 配置:

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

在 IoC 容器中注册 Controller 与 MVC 集成相同:

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

关于c# - 如何将 WebApi 2 与 Spring.Net 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29930847/

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