仅通过 Ninject 将存储库绑定到基类?
我有一个基类,它有一个存储库注入到构造函数中,现在我从它派生的任何类现在也需要这些参数,但存储库仅由基类使用,有没有办法将 Ninject 绑定到基类而不通过构造函数?最重要的是,这是一个好主意吗?
public class HtmlPageModel
{
private readonly IHtmlPageRepository _repository;
public HtmlPageModel (IHtmlPageRepository repository)
{
_repository = repository;
}
}
public class VideoPageViewModel : HtmlPageModel
{
public VideoPageViewModel(IHtmlPageRepository repository) : base(repository)
{
}
}
I have a base class that has a repository injected into the constructor, now any class that I derive off of it now also needs those parameters, but the repository is only used by the base class, is there a way to bind Ninject to just the base class and not go through the constructor? And most importantly, is it a good idea?
public class HtmlPageModel
{
private readonly IHtmlPageRepository _repository;
public HtmlPageModel (IHtmlPageRepository repository)
{
_repository = repository;
}
}
public class VideoPageViewModel : HtmlPageModel
{
public VideoPageViewModel(IHtmlPageRepository repository) : base(repository)
{
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我仍然坚持我之前的评论:你必须重新考虑你的类层次结构,这不是你应该使用 Ninject 解决的问题。
如果您的基类接受存储库,那么所有派生类也应该接受存储库。作为替代方案,您可以将一个特殊的
NullRepository
注入到您的VideoPageViewModel
中,它基本上不执行任何操作(请参阅空对象模式)可以使用 Ninject 中的
WhenInjectedInto()
来实现按目标类型的绑定:I still stand to my previous comment: You have to rethink your class hierarchy, this is not something you should work around with Ninject.
If your base class accepts a repository, so should all of your derived classes. As an alternative you could however inject a specially
NullRepository
into yourVideoPageViewModel
which basically does nothing (see Null Object pattern)Binding by target type can be achieved using
WhenInjectedInto()
in Ninject:这与brokenGlass 的答案基本相同。为什么不直接创建另一个基类,并将属性/功能从当前基类移动到该基类中,但不要移动与存储库相关的构造函数/功能。
This is basically the same answer as brokenGlass. Why not just create another base class, and move the attributes/functionality from the your current base class into that one, but don't move the constructor/functionality that relates to the repository.
视图模型根本不应该有依赖关系。将存储库注入控制器并从那里分配值。
此外,如果许多页面使用相同的基本视图模型,则这表明页面的某些部分在许多情况下甚至始终显示。在这种情况下,最好为该区域提供一个自定义控制器和视图,并使用
Html.RenderAction
来渲染该部分。View models shouldn't have dependencies at all. Inject the repository into the controller and assign the values from there.
Also if many pages are using the same base view model this indicates that some part of the page is shown in many situations or even all the time. In this case it is better to have a custom controller and view for this area and use
Html.RenderAction
to render this part.