是否可以指示 Ninject 将基于上下文的逻辑应用于所有绑定?

发布于 2024-08-29 05:03:28 字数 559 浏览 6 评论 0原文

我们最近开始使用依赖注入,并且我们选择 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 技术交流群。

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

发布评论

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

评论(1

君勿笑 2024-09-05 05:03:28

您可以使用约定扩展执行以下操作

var kernel = new StandardKernel();
kernel.Scan( x=>
             {
                 x.FromAssemblyContaining<MyEntityMapper>();
                 x.FromCallingAssembly();
                 x.WhereTypeInheritsFrom<IEntityMapper>();
                 x.InSingletonScope();
             } );

You can use the conventions extension to do the following

var kernel = new StandardKernel();
kernel.Scan( x=>
             {
                 x.FromAssemblyContaining<MyEntityMapper>();
                 x.FromCallingAssembly();
                 x.WhereTypeInheritsFrom<IEntityMapper>();
                 x.InSingletonScope();
             } );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文