I use this contract resolver for dependency-injection with Autofac
and Json.NET
:
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;
}
}
Then, I use it with DI to initialize the JsonSerializer
:
var contractResolver = ctx.Resolve<IContractResolver>(); // ctx = Autofac's IComponentContext
var jsonSerializer = new JsonSerializer
{
ContractResolver = contractResolver, // <-- AutofacContractResolver
};
What would be the equivalent of this technique with the new System.Text.Json in net-core-3.0
- if there is any already? I wasn't able to figure this out and couldn't find any interfaces that would look similar to this ones.