I have a XmlSerializer
and a JsonSerializer
where a factory should decide which one to instantiate based on command line parameter "json" or "xml". Pretty easy but I would like to do this with Ninjects Factory extensions.
So this is what I have working now:
Bind<ISerializerFactory>().ToFactory(() => new UseFirstArgumentAsNameInstanceProvider());
Bind<ISerializer>().To<XmlSerializer>().Named("xml");
Bind<ISerializer>().To<JsonSerializer>().Named("json");
In Composition Root I instantiate the serializer like this:
kernel.Get<ISerializerFactory>().CreateSerializer(options.ContentFormat);
So far so good.
Now I introduced something like a strategy pattern to set behaviour to a few properties of the ISerializer
classes, like:
concreteSerializer.BehaviourA = new Behaviour();
These behaviours should be instantiated by a factory too since the behaviour is given by the user at runtime.
So I did the same factory configuration like I did with the serializer itself already.
But I want to set the behaviour instantiated by the IBehaviourFactory
within the first ISerializerFactory
.
So I tried something like this:
Bind<ISerializer>().ToMethod(context =>
{
var xmlSerializer = context.Kernel.Get<XmlSerializer>();
var behaviourFactory = context.Parameters.First(x => x.Name == "behaviourFactory").GetValue(context, <ITarget??>) as IBehaviourFactory;
xmlSerializer.BehaviourA = behaviourFactory.CreateBehaviour(optionsFromSomewhere);
return xmlSerializer;
}).Named("xml");
But I can't get it to work.
How should I set the Behaviour to the serializer when creating the serializer instance? How should I solve such scenarios in general?
Thanks for any hints!