0

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!

dasheddot
  • 2,936
  • 4
  • 26
  • 33
  • Would it be an alternative to have it created by an abstract-factory like pattern like here: http://stackoverflow.com/questions/20954481/how-to-implement-an-gof-ish-abstract-factory-pattern-using-an-ioc-like-ninject/20968400#20968400 ? – BatteryBackupUnit Jun 24 '14 at 05:32
  • Tried to investigate if this is what I want, but I didn't come to any conclusions ;-) Would be nice if you find the time to explain shortly how abstract factory pattern would solve my issues. I am fiddling around with the pattern meanwhile.. – dasheddot Jun 24 '14 at 14:30
  • (i was away for a few days). From your question i'm not entirely certain on when what should be instantiated. Am i correct in assuming, that both the serializer type (xml/json) and the behavior type are passed as cmd-line args? The `ISerializer` instance should be built up completely - including behavior - at once? so you would like a factory you'd use like `ISerializer IFactory.Create("xml", "typeA")`? (For future reference: it would be helpful to always state one's goal clearly, like how the interface should look like). – BatteryBackupUnit Jun 27 '14 at 05:18

0 Answers0