3

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?

Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
icedtoast
  • 128
  • 2
  • 10

1 Answers1

2

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>();
Ruben Bartelink
  • 59,778
  • 26
  • 187
  • 249
Remo Gloor
  • 32,665
  • 4
  • 68
  • 98
  • thanks, I would prefer not to have to add an extension to the project, is there a way I can "manually" create a child request preserving the context? – icedtoast Oct 02 '11 at 22:27
  • 1
    Why don't you want to add an extension? They are part of the Ninject project. And sure there is a way to do it manually. Do exactly what is done in the extension. But this way you will have to maintain your code yourself. – Remo Gloor Oct 03 '11 at 00:46