开发者

Ninject Binding Constraint that searches up to find a type

开发者 https://www.devze.com 2023-04-07 05:54 出处:网络
I\'ve got a class hierarchy like this (simplified): class Connection { } interface IService<T> { } class ServiceImplementation : IService<int>

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开发者_如何学JAVA 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?


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>();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号