Ninject:抽象类
我是否需要在抽象类中做一些不同的事情才能使依赖注入与 Ninject 一起使用?
我有一个包含以下代码的基本控制器:
public abstract class BaseController : Controller
{
public IAccountRepository AccountRepository
{
get;
set;
}
}
我的模块如下所示:
public class WebDependencyModule : NinjectModule
{
public override void Load()
{
Bind<IAccountRepository>().To<AccountRepository>();
}
}
这是我的 Global.asax
:
protected override void OnApplicationStarted()
{
Kernel.Load(new WebDependencyModule());
}
protected override IKernel CreateKernel()
{
return new StandardKernel();
}
当我用 装饰
属性。IAccountRepository
属性时,它可以工作>[注入]
Do I need to do something different in an abstract class to get dependency injection working with Ninject?
I have a base controller with the following code:
public abstract class BaseController : Controller
{
public IAccountRepository AccountRepository
{
get;
set;
}
}
My module looks like this:
public class WebDependencyModule : NinjectModule
{
public override void Load()
{
Bind<IAccountRepository>().To<AccountRepository>();
}
}
And this is my Global.asax
:
protected override void OnApplicationStarted()
{
Kernel.Load(new WebDependencyModule());
}
protected override IKernel CreateKernel()
{
return new StandardKernel();
}
It works when I decorate the IAccountRepository
property with the [Inject]
attribute.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不确定你想做什么。
看来您想要进行属性注入。如果是这样,您必须坚持该属性。
Ninject 不会随机将东西粘贴到属性中。
即使可以,从试图理解什么依赖于什么的角度来看,你也不会希望它这样做(我已经完全摆脱了 PI)。
如果你想进行构造函数注入,具体的控制器将需要请求一个并将其传递给“BaseController”。
Ninject 将遍历对象并注入属性属性,但不会以任何特殊方式处理抽象类。
要么就是我错过了一些东西。
Not sure what you're trying to do.
It looks like you want to do Property Injection. If so, you have to stick on the attribute.
Ninject doesnt randomly go sticking things in properties.
Even if it could, you wonldnt want it to from the point of view of trying to understand what depends on what (I've weaned myself completely off PI).
If you want to do constructor injection, the concrete Controller will need to ask for one and pass it down to 'BaseController'.
Ninject will walk through to
Object
and inject Attributed properties, but doesnt treatabstract
classes in any special manner.Either that or I'm missing something.