这就是我现在想出的,它有效。
我决定创建一个自定义格式化程序,它执行统一调用并将所有进一步的操作转发到另一个使用已解析类型的格式化程序。它看起来像很多代码,但这只是因为所有方法都需要被覆盖,所以类型总是可以被解析。
public class UnityFormatter : MediaTypeFormatter
{
private MediaTypeFormatter formatter;
private IUnityContainer container;
public UnityFormatter(MediaTypeFormatter formatter, IUnityContainer container)
{
this.formatter = formatter;
this.container = container;
foreach (var supportedMediaType in this.formatter.SupportedMediaTypes)
{
this.SupportedMediaTypes.Add(supportedMediaType);
}
foreach (var supportedEncoding in this.formatter.SupportedEncodings)
{
this.SupportedEncodings.Add(supportedEncoding);
}
foreach (var mediaTypeMapping in this.MediaTypeMappings)
{
this.MediaTypeMappings.Add(mediaTypeMapping);
}
this.RequiredMemberSelector = this.formatter.RequiredMemberSelector;
}
private Type ResolveType(Type type)
{
return this.container.Registrations.Where(n => n.RegisteredType == type).Select(n => n.MappedToType).FirstOrDefault() ?? type;
}
public override bool CanReadType(Type type)
{
return this.formatter.CanReadType(this.ResolveType(type));
}
public override bool CanWriteType(Type type)
{
return this.formatter.CanWriteType(this.ResolveType(type));
}
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
return this.formatter.GetPerRequestFormatterInstance(this.ResolveType(type), request, mediaType);
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
return this.formatter.ReadFromStreamAsync(this.ResolveType(type), readStream, content, formatterLogger);
}
public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
{
this.formatter.SetDefaultContentHeaders(this.ResolveType(type), headers, mediaType);
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
return this.formatter.WriteToStreamAsync(this.ResolveType(type), value, writeStream, content, transportContext);
}
}
最后,在应用程序配置(Global.asax Application_Start)中注册我们的自定义格式化程序。我选择用我自定义的一个实例替换所有当前的格式化程序,所以我得到了所有数据类型的反射。
// set up unity container, register all types
UnityContainer container = new UnityContainer();
container.RegisterType<IApiRegistrationRequest, ApiRegistrationRequest>();
// save existing formatters and remove them from the config
List<MediaTypeFormatter> formatters = new List<MediaTypeFormatter>(GlobalConfiguration.Configuration.Formatters);
GlobalConfiguration.Configuration.Formatters.Clear();
// create an instance of our custom formatter for each existing formatter
foreach (MediaTypeFormatter formatter in formatters)
{
GlobalConfiguration.Configuration.Formatters.Add(new UnityFormatter(formatter, container));
}