开发者

How do you use method injection with Ninject?

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


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.


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜