I'm writing a simple windows service, and I want to use a Dependency Injection. On service start, the app read the JSON string from file, and deserialize it to object. One of property in JSON is list of 'Bar' objects, and in 'Bar' constructor I want to inject FooService. I suspected that following code will works, but 'service' in 'Bar' constructor is null.
Can anyone expalin me, why this code not working, and how to change it to works?
That's my code:
NinjectBinding.cs
class NinjectBindings : Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind<IFooService>().To<FooService>();
Bind<Bar>().ToSelf().WithConstructorArgument("service", ctx => ctx.Kernel.Get<IFooService>());
}
}
Deserializator.cs
internal class Deserializator
{
internal static void GetFilePaths()
{
var json = JsonConvert.DeserializeObject<Deserializator>("{}");///... Read from JSON File
}
public List<Bar> BarList { get; set; }
}
Bar.cs
public class Bar {
private readonly IFooService _fooService;
public Bar (IFooService service){
// here service is null
using (var kernel = new StandardKernel(new NinjectBindings())){
var kernelService = kernel.Get<IFooService>();
// here kernelService is NOT null
}
}
}
UPDATE
I found solution on https://www.newtonsoft.com/json/help/html/DeserializeWithDependencyInjection.htm
I've added NinjectResolver.cs
class NinjectResolver : DefaultContractResolver
{
private readonly IKernel _container;
public NinjectResolver(IKernel container)
{
_container = container;
}
protected override JsonObjectContract CreateObjectContract(Type objectType)
{
if (_container.TryGet(objectType) != null)
{
JsonObjectContract contract = ResolveContact(objectType);
contract.DefaultCreator = () => _container.Get(objectType);
return contract;
}
return base.CreateObjectContract(objectType);
}
private JsonObjectContract ResolveContact(Type objectType)
{
return base.CreateObjectContract(objectType);
}
}
remove Bind from NinjectBindings, and change SerializationMethod to:
var json = JsonConvert.DeserializeObject<Deserializator>("{}", new
JsonSerializerSettings()
{
ContractResolver = new NinjectResolver(new StandardKernel(new NinjectBindings()))
});
And now - it works.