简体   繁体   中英

Ninject Providers: what is the correct way to resolve dependencies

In my application I can register different datasources by name. These data-sources each have a few string properties required, along with a set of other dependencies, but are otherwise the same, so take a few different standard implementations.

To construct instances of each datasource when requested, I create a binding to an instance of a Provider<T> which is initialized with the information required to access that data-source. The provider looks something like the below:

public class StandardListProvider<T> : Provider<IListExecutor<T>>
    where T : new()
{
    public string Name       { get; set; }
    public string ListMethod { get; set; }

    public StandardListProvider(string name, string listMethod)
    {
        Name       = name;
        ListMethod = listMethod;
    }

    protected override IListExecutor<T> CreateInstance(IContext context)
    {
        var connector = (IInternalConnector)context.Kernel.GetService(typeof(IInternalConnector));
        return new StandardListExecutor<T>(connector, Name)
        {
            ListMethodName = ListMethod
        };
    }
}

The problem is with resolving dependencies of the StandardListExecutor<T> like IInternalConnector . Obviously I can construct them manually, or request them from context.Kernel as I am in my example (and suggested by Ninject Providers -> Get another dependency inside the provider ), but this results in a request with no Target information, which is not ideal if we want to perform contextual bindings for the dependencies of StandardListExecutor .

I've tried playing with context.Request.CreateChild(...) , but this appears to require reflection on every activation to create a ParameterTarget . There doesn't appear to be much information about this in the Ninject docs either.

My question is: What is the correct way to resolve/request dependencies, or other services like this from within the activation process of an existing binding?

Edit

The requests themselves are made via the Ninject.Mvc hookups into the System.Web.Mvc controller activation process.

You should be able to use the extension Ninject.Extensions.ContextPreservation . Specifically the extension method IContext.ContextPreservingGet(...) :

var connector = context.ContextPreservingGet<IInternalConnector>();

However, personally I think that creating specific settings types is the better choice - because it's the simpler idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM