将依赖项注入基类

发布于 2024-09-03 04:17:00 字数 372 浏览 4 评论 0原文

我从依赖注入开始,在将依赖项注入基类时遇到一些问题。

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纵山崖 2024-09-10 04:17:00

你的 BaseController 构造函数应该像这样

BacseConctoller(Info info)
{
    this.info = info
}

对于所有继承类,
在这种

ChildController(Info info):base(info)
{
}

情况下,您可以将 Info 对象注入到控制器基类中

your BaseController constructor should be like this

BacseConctoller(Info info)
{
    this.info = info
}

then for all inheritence class
their constructor

ChildController(Info info):base(info)
{
}

in this case you can inject Info object to the base controller class

眼前雾蒙蒙 2024-09-10 04:17:00

马克是对的,

BaseClass(dependantObject object)
{
 Object = object;
}

所以为了实现 dependentObject 以便所有子类都可以访问基本行为,我们可以在子类上使用注入并简单地链接基本构造函数,传入我们的“Ninjected”对象。

 SubClass() : this(null) {}

 SubClass(dependantObject object) : base(object)
  {

  }

快乐编码!

Mark is right on the money,

BaseClass(dependantObject object)
{
 Object = object;
}

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.

 SubClass() : this(null) {}

 SubClass(dependantObject object) : base(object)
  {

  }

happy coding!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文