将依赖项注入基类
我从依赖注入开始,在将依赖项注入基类时遇到一些问题。
我有一个 BaseController 控制器,我的其他控制器继承自该控制器。在此基本控制器内部,我执行了许多检查,例如确定用户是否具有查看当前页面的正确权限、检查某些会话变量是否存在等。
我在此基本控制器内部有一个依赖项喜欢使用 Ninject 注入,但是当我像其他依赖项一样设置它时,编译器告诉我:
错误 1“MyProject.Controllers.BaseController” 不包含构造函数 接受 0 个参数
这是有道理的,但我只是不确定如何注入这个依赖项。我应该使用这种使用基本控制器的模式还是应该以更有效/正确的方式执行此操作?
I'm starting out with Dependency Injection and am having some trouble injecting a dependency into a base class.
I have a BaseController
controller which my other controllers inherit from. Inside of this base controller I do a number of checks such as determining if the user has the right privileges to view the current page, checking for the existence of some session variables etc.
I have a dependency inside of this base controller that I'd like to inject using Ninject however when I set this up as I would for my other dependencies I'm told by the compiler that:
Error 1 'MyProject.Controllers.BaseController'
does not contain a constructor that
takes 0 argument
This makes sense but I'm just not sure how to inject this dependency. Should I be using this pattern of using a base controller at all or should I be doing this in a more efficient/correct way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的 BaseController 构造函数应该像这样
对于所有继承类,
在这种
情况下,您可以将 Info 对象注入到控制器基类中
your BaseController constructor should be like this
then for all inheritence class
their constructor
in this case you can inject Info object to the base controller class
马克是对的,
所以为了实现 dependentObject 以便所有子类都可以访问基本行为,我们可以在子类上使用注入并简单地链接基本构造函数,传入我们的“Ninjected”对象。
快乐编码!
Mark is right on the money,
so to fulfill the dependantObject so all the subclasses can get access to the base behavior, we can use the injection on the subclass and simply chain the base constructor, passing in our 'Ninjected' object.
happy coding!