How do you use method injection with Ninject?

左心房为你撑大大i 提交于 2019-12-04 05:41:48

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!