将自定义 TypeConverter 限制为特定程序集

Restrict custom TypeConverter to a specific assembly

我已经定义了自定义 TypeConverter 和关联的自定义 TypeDescriptionProviderTypeDescriptor 以便在从 REST Web 服务返回值时我的类型自动转换为字符串(使用 ASP.NET 核心).

但是,我现在注意到在我的应用程序的其他地方(例如,当我序列化 XML 保存我的配置文件,或在 WPF 中加载 XAML 时)我的自定义 TypeConverter 正在呼叫中。

有没有办法限制我的自定义类型转换器/描述提供者/描述符,以便它们仅在我的 Web 服务程序集中使用?


更多信息

我的内部对象没有使用 [TypeConverter()] 属性来指定要使用的类型转换器。

如答案所示,我正在使用 AutoMapper 进行从内部对象到数据传输对象的映射。 AutoMapper 利用 TypeDescriptor/TypeConverter,自动将我的对象的属性映射到字符串。我希望行为是 只有 AutoMapper 使用此自定义类型转换器。

但是,类型转换器似乎是全局注册的:TypeDescriptor.AddProvider(customerProvider, myType)

我看不出有什么方法可以将其限制在某些组件上。到目前为止,我唯一的想法是以某种方式使用 ICustomTypeDescriptorGetComponentName()(但这似乎总是 null)或 运行 我的 Web 服务器在单独的 AppDomain,我假设它使用单独的类型转换器,但可能会给 marshalling/serialization 带来巨大的问题。还有其他解决方案吗?

一旦属性在您的模型上被硬编码,那么在运行时将很难 change/modify/disable,并且无法删除。在您的情况下,即使在 Web 应用程序中,您也无法禁用或删除这些属性。

我给你一个选择,AutoMapper,多年来我一直用它来做转换作业,尤其是MVXX模式,无论ASP.NET MVC还是WPF MVVM,两者都是需要将 view models 转换为 real models。 AutoMapper 通过配置而不是属性应用转换器,这使您的请求成为可能。

https://github.com/AutoMapper/AutoMapper/blob/master/docs/Custom-type-converters.md

Mapper.Initialize(cfg => {
  cfg.CreateMap<ModelA, string>().ConvertUsing(new ModelAToStringTypeConverter());
  cfg.CreateMap<ModelA, ModelB>().ConvertUsing(new ModelAToBTypeConverter());
  cfg.CreateMap<ModelB, ModelA>().ConvertUsing(new ModelBToATypeConverter());
  ....
  cfg.AddProfile<WpfProfile>();
});

public class WpfProfile: Profile
{
    public OrganizationProfile()
    {
        CreateMap<Foo, FooDto>();
        // Use CreateMap... Etc.. here (Profile methods are the same as configuration methods)
    }
}

如果 ModelA 的属性是 ModelB 的一个子集,您甚至不需要对转换器进行硬编码,cfg.CreateMap<ModelB, ModelA>() 会自动执行此操作。

AutoMapper 提及 this:

The .NET Framework also supports the concepts of type converters, through the TypeConverter class. AutoMapper supports these types of type converters, in configuration checking and mapping, without the need for any manual configuration. AutoMapper uses the TypeDescriptor.GetConverter method for determining if the source/destination type pair can be mapped.