0

I have a situation where I need to determine the type of parameter passed to a parent object in Ninject.

Here is an example with a Parent, a Child and a ParentFactory that is responsible for creating it all...

public interface IParentFactory
{
    Parent Create(IConfig config);
}

public interface IConfig
{
    // ...
}

public class ConfigForChildOfType1 : IConfig
{
   // ....
}

public class ConfigForChildOfType2 : IConfig
{
   // ....
}

public class Parent
{
    public Parent(IChild child)
    {
        ...
    }
}

public interface IChild
{
}

public class Child1 : IChild
{
    // Some stuff
}

public class Child2 : IChild
{
    // Some stuff
}

When binding to create the Parent, I have bound using the ToFactory method:

Bind<IParentFactory>().ToFactory();
Bind<Parent>().ToSelf();

This makes it possible to call:

var factory = kernel.Get<IParentFactory>();

...to get my factory.

When I use the factory, I can use...

var parentInstance = factory.Create(new ConfigForChildOfType1()); // Bad example with "new", but anyway

Now - here is my problem. When the factory creates the Parent instance, using the configuration passed, I want the type of child to be created depending on the type of config.

So, can I, when the IChild is created, check to see what parameters the parent constructor was called with - i.e. can I see which type of configuration that was passed to the factory's create method?

ForestC
  • 213
  • 1
  • 12
  • 1
    I think you are looking for [Contextual Binding](https://github.com/ninject/ninject/wiki/Contextual-Binding). – Steven May 25 '13 at 11:34
  • I solved this by Metadata properties, but it looks a bit "ugly". I could not find a good solution when using Contextual Binding. – ForestC May 26 '13 at 15:28

0 Answers0