我使用此契约(Contract)解析器通过 Autofac
和 Json.NET
进行依赖注入(inject):
public class AutofacContractResolver : DefaultContractResolver
{
private readonly IComponentContext _container;
public AutofacContractResolver(IComponentContext context)
{
_container = context ?? throw new ArgumentNullException(nameof(context));
}
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
// use Autofac to create types that have been registered with it
if (_container.IsRegistered(objectType))
{
contract.DefaultCreator = () => _container.Resolve(objectType);
}
return contract;
}
}
然后,我使用它和 DI 来初始化 JsonSerializer
:
var contractResolver = ctx.Resolve<IContractResolver>(); // ctx = Autofac's IComponentContext
var jsonSerializer = new JsonSerializer
{
ContractResolver = contractResolver, // <-- AutofacContractResolver
};
这种技术与新的 System.Text.Json 的等价物是什么?在 net-core-3.0
中 - 如果已经有的话?我无法弄清楚这一点,也找不到任何看起来与此相似的界面。
最佳答案
请尝试我编写的这个库作为 System.Text.Json 的扩展以提供缺少的功能:https://github.com/dahomey-technologies/Dahomey.Json .
您会发现对编程对象映射的支持。
定义您自己的 IObjectMappingConvention 实现:
public class AutofacObjectMappingConvention : IObjectMappingConvention
{
private readonly IComponentContext _container;
public AutofacObjectMappingConvention(IComponentContext context)
{
_container = context ?? throw new ArgumentNullException(nameof(context));
}
public void Apply<T>(JsonSerializerOptions options, ObjectMapping<T> objectMapping) where T : class
{
defaultObjectMappingConvention.Apply<T>(options, objectMapping);
// use Autofac to create types that have been registered with it
if (_container.IsRegistered(objectType))
{
objectMapping.MapCreator(o => _container.Resolve<T>());
}
}
}
实现 IObjectMappingConventionProvider 以将多个类型关联到约定:
public class AutofacObjectMappingConventionProvider : IObjectMappingConventionProvider
{
public IObjectMappingConvention GetConvention(Type type)
{
// here you could filter which type should be instantiated by autofac and return null for other types
return new AutofacObjectMappingConvention();
}
}
通过在 JsonSerializerOptions 上调用命名空间 Dahomey.Json 中定义的扩展方法 SetupExtensions 来设置 json 扩展:
JsonSerializerOptions options = new JsonSerializerOptions();
options.SetupExtensions();
为类注册新的对象映射约定:
options.GetObjectMappingConventionRegistry().RegisterProvider(new AutofacObjectMappingConventionProvider());
然后使用常规 Sytem.Text.Json API 序列化您的类:
string json = JsonSerializer.Serialize(myClass, options);
关于c# - 使用新的 .net-core-3 json 序列化程序进行依赖注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837182/