Skip to content

Instantly share code, notes, and snippets.

@lasandell
Last active May 3, 2016 18:14
Show Gist options
  • Save lasandell/6df8fe1c65732d2571f4891f57621842 to your computer and use it in GitHub Desktop.
Save lasandell/6df8fe1c65732d2571f4891f57621842 to your computer and use it in GitHub Desktop.
using System;
using Autofac;
using Newtonsoft.Json.Serialization;
/// Allows constructor dependencies to be resolved when deserializing JSON.NET instances.
public class DependencyContractResolver : DefaultContractResolver
{
/// But what if I wanted to extend CamelCasePropertyNamesContractResolver instead of
/// DefaultContractResolver in some cases? No way to switch it out without delegation.
private readonly ILifetimeScope _scope;
public DependencyContractResolver(ILifetimeScope scope)
{
_scope = scope;
}
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
var contract = base.CreateObjectContract(objectType);
if (_scope.IsRegistered(objectType))
contract.DefaultCreator = () => _scope.Resolve(objectType);
return contract;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment