Search code examples
ninjectninject-extensions

Ninject - Resolve instance per method call


I'm finding a solution to resolve an instance per method call. Something like that:

public class ServiceAPI
{
    public void ServiceAction()
    { 
        //Call certain repository action
        // Ex: 
        Kernel.Get<RepositoryA>().Insert();

    }
}

public class RepositoryA
{
    public void Insert(object a)
    { 
        //Get logger per service call ?
        var logger = Kernel.Get<RepositoryA>().Insert();

    }
}

I wanna the logger instance created one time per service call and it will be used throughout the repository. I try with Ninject.Extensions.NamedScope extensions but it haven't worked yet. Can you have any way to deal with this scenario ?


Solution

  • It is not possible to achieve this by using a scoping mechanism. (InCallScope(), InNamedScope(...),...). Scoping is only relevant when ninject is calling the constructor of a type. Ninject cannot - ever - replace the instance that is already passed to an object. If you want to do this you have to program it yourself.

    Here's two design alternatives how you can achieve what you want:

    • instantiate an object tree per method invocation. If there's some service infrastructure like WCF or Web-API there are probably hooks which can be used to do so.
    • replace the object which should be instantiated per method call by a proxy. The proxy can then use Ninject to create the target for each method call and execute the method on it.

    For proxying you can use tools like Castle DynamicProxy or LinFu. There's also Ninject.Extensions.Interception which may also be helpful.