我试图将 WebApi 2 与 Spring.Net 集成,但没有成功。这就是我的尝试:
private static void Main(string[] args)
{
var dataGeneratorList = new List<DataGenerator>
{
new StringDataGenerator(Name.First, "first", "name"),
new StringDataGenerator(Name.Last, "last", "name"),
new GuidDataGenerator(Guid.NewGuid, "uid", "id")
};
var writeProperties = typeof (Employee).GetProperties().Where(p => p.CanWrite);
foreach (var property in writeProperties)
{
foreach (var dataGenerator in dataGeneratorList)
{
if (property.PropertyType == dataGenerator.Type)
{
var weigth = dataGenerator.GetWeight(property.Name);
//How to access generator here???
var testValue = dataGenerator.Generator.Invoke();
}
}
}
}
何时创建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);
}
}
实例,我得到此异常:
创建上下文时遇到错误&#39; spring.root&#39;:请求在此上下文中不可用
SpringWebApiDependencyResolver
我正在使用Spring.Net 2.0.1
答案 0 :(得分:4)
现在正在运作,不需要以下一行:
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容器中注册控制器与MVC集成相同:
<object type="namespace.PrefixController, assemblyName" singleton="false" >
<property name="Dependency1" ref="Dependency1" />
</object>