3
votes

I've got a class hierarchy like this (simplified):

class Connection
{
}

interface IService<T>
{
}


class ServiceImplementation : IService<int>
{
   public ServiceImplementation(Connection)
   {
   }
}

interface IConnectionConfiguration
{
   public void Configure(Connection c)
}

class ConnectionConfiguration : IConnectionConfiguration
{
   public void Configure(Connection c)
}

Where I have multiple implementations of IConnectionConfiguration and IService. I am wanting to create a provider/bindings which:

  1. constructs a new instance of Connection.
  2. GetAll and applies that to the Connection.
  3. Bindings specify which IConnectionConfiguration implementations to be used, based on on the type of IService to be constructed

Currently I have a provider implementation like this:

public Connection CreateInstance(IContext context)
{
     var configurations = context.Kernel.GetAll<IConnectionConfiguration>()
     var connection = new Connection();
     foreach(var config in configurations)
     {
        config.Configure(connection);
     }

     return connection;
}

But when I try to make the contextual binding for IConnectionConfiguration it doesn't have a parent request or parent context...

Bind<IConnectionConfiguration>().To<ConcreteConfiguration>().When(ctx => {
 // loop through parent contexts and see if the Service == typeof(IService<int>);
 // EXCEPT: The ParentRequest and ParentContext properties are null.
});

What am I doing wrong here? Can I do this with ninject?

1

1 Answers

2
votes

By calling kernel.GetAll you are creating a new request. It has no information about the service context. There is an extension that allows you to create new requests that preserve the original context (Ninject.Extensions.ContextPreservation)

See also https://github.com/ninject/ninject.extensions.contextpreservation/wiki

context.GetContextPreservingResolutionRoot().GetAll<IConnectionConfiguration>();