0

我从 Ninject 开始,我在 MVC 4 场景中使用它,并在“NinjectWebCommon”中配置了我的绑定。一切正常。

现在我想在一个库中以某种方式从 MVC 应用程序中获取具有配置的内核。

例如:在我的 MVC 项目中,我有一个带有属性的类“BaseController”

[Inject]
public IKernel Ninject { get; set; }

完美运行,这意味着在从 BaseController 继承的控制器中的每个操作中,属性“Ninject”都是很好的实例而不是 null!

现在我的外部库中有类“NinjectProxy”,具有完全相同的属性,但每次我创建一个新的“NinjectProxy”实例时,道具“Ninject”都是空的!

public class NinjectProxy
{
    [Inject]
    public IKernel Ninject { get; set; }


    public T Resolve<T>()
    {
        return Ninject.Get<T>();
    }
}

我的完整解决方案如下所示:

MVC app
- Reference on Common.dll and Ninject
- Contains ControllerBase
Common.dll
- This project contains the NinjectProxy class and have a reference on Ninject
- Here I want somehow get the kernel config that I configured in the mvc app to resolve dependecies
Implementation.dll
- References on Common.dll and Ninject

该库在“NinjectWebCommon”中加载:

kernel.Load(Assembly.Load("lib"))

如果这很重要。

有人知道我做错了什么吗?

4

1 回答 1

0

您正在使用手动创建实例new此对象不由 ninject 处理,并且永远不会获得依赖项。

将实例注入某处,或使用工厂由 ninject 创建

但是鲁本是绝对正确的,您正在遵循一种无论如何都不应该使用的模式。而是在引导程序中完全配置 Ninject。要么使用与整个项目匹配的约定,要么引用所有必需的程序集并为它们设置绑定。

于 2013-02-20T11:45:20.083 回答