How do you use method injection with Ninject?
Asked Answered
S

2

6

I have a class which needs to use an IRepository for one method in it's class.

Ideally, I would like to avoid having to resolve this dependency into the class's constructor, and so I found method level injection in Ninject and was wondering how this works?

I understand how to set it up. What I'm confused about is how to call it?

Example:

class SomeClassThatUsesRepository
{
    [Inject]
    public void QueryForSomeStuff(IRepository repository)
    {
        //do some stuff
    }
}

My problem is how do I call this method without specifying an IRepository?

var someClass = Kernel.Resolve<SomeClassThatUsesRepository>();

would work if I was using the constructor, but I want to call a method.

How do I call a method using Ninject method injection?

Sora answered 3/11, 2010 at 20:13 Comment(0)
C
13

I'm afraid method injection doesn't work this way - it's just one of the ways to inject dependencies into an object during its construction (you can inject your dependencies through constructor parameters, through properties, fields or methods). Method injection is useful if your class takes its dependencies by Java-style setter methods like

public void SetRepository(IRepository repository) { ... }

If it is marked with [Inject] attribute, you don't need to call this methods directly, it is to be called by Ninject during the initialization to pass the IRepository object into your resolved object.

So I believe your QueryForSomeStuff method is being called when you resove your SomeClassThatUsesRepository.

Cowman answered 3/11, 2010 at 21:31 Comment(1)
+1 great explanation. I'd only mention that it mimicks two phase construction - i.e., as if the method was called Initialize()Venue
N
0

Confirmed that method injection doesn't work as intended. Got a custom MVC attribute class and wanted to use an injected object inside it. Did not pass it into the constructor and added method

[Ninject.Inject]
public void ResolveDI(ISettingStore store)
{
    ConfigHelper = store;
}

This method was never called and ConfigHelper was null when the attribute's OnActionExecuting was called.

Noninterference answered 17/4, 2017 at 20:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.