是否可以指示 Ninject 将基于上下文的逻辑应用于所有绑定?
我们最近开始使用依赖注入,并且我们选择 Ninject 2(目前)作为我们的 IoC 容器。当我重构我们的解决方案以纳入 DI 原则时,我遇到了一些让我有点烦恼的事情,我想知道是否有一种简单的方法来解决它。
对于我们的数据层,我们有一大堆继承相同通用类(EntityMapper)的数据访问类。虽然过去我们总是在需要时构建这些类的新实例,但它们实际上都可以更改为单例。我们已经重写了 ObjectDataSource 以使用 Ninject 实例化其数据访问对象,因此每当我们创建指向 EntityMapper 类之一的 ObjectDataSource 时,Ninject 都会使用其默认的自绑定策略来注入必要的依赖项。由于这些类如此之多,我们宁愿不必为每个 EntityMapper 类创建显式绑定,也不必为每个类添加特殊属性。但是,我希望能够指示 Ninject 将 EntityMapper 的任何实例制作为单例类。像这样的事情:
Bind(t => typeof(IEntityMapper).IsAssignableFrom(t)).InSingletonScope();
有什么办法可以做到这一点吗?
We've begun using Dependency Injection recently, and we've chosen Ninject 2 (for now) as our IoC Container. As I refactor our solution to incorporate DI principles, I've run into something that bugs me a little, and I'm wondering if there's an easy way to get around it.
For our data layer, we have a whole bunch of data-access classes that inherit the same generic class (EntityMapper). While in the past we've always constructed a new instance of these classes when we needed one, they really could all be changed into Singletons. We've overridden ObjectDataSource to use Ninject to instantiate its data-access object, so any time we create an ObjectDataSource that points to one of our EntityMapper classes, Ninject will use its default self-binding strategy to inject the necessary dependencies. Since there are so many of these classes, we'd rather not have to create an explicit binding for each of our EntityMapper classes, and we'd rather not have to put a special attribute on every one of them either. However, I would like to be able to instruct Ninject to make any instance of EntityMapper into a singleton class. Something like this:
Bind(t => typeof(IEntityMapper).IsAssignableFrom(t)).InSingletonScope();
Is there any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用约定扩展执行以下操作
You can use the conventions extension to do the following