StructureMap 注入的 IContainer - 它来自哪里?

发布于 2024-09-15 09:33:29 字数 214 浏览 1 评论 0原文

我有一个 ASP.Net MVC 应用程序,我在 MVC 中使用 StructureMap 将整个应用程序粘合在一起。有些模型类具有重量级依赖项,但并未在所有公共方法中使用,因此我将 IContainer 传递给模型构造函数,并使用它来根据需要创建重量级依赖项。

我的问题是注入的 IContainer 从哪里来?它是对 MVC (它的逻辑父级)集中保存的引用,还是专门为此类创建和配置的全新引用?

I have an ASP.Net MVC application and I am using StructureMap within MVC to glue the whole application together. There are some model classes that have heavyweight dependencies that are not used in all public methods, so I pass in an IContainer to the model constructor and use that to create the heavyweight dependencies on demand.

My question is where does the IContainer come from that is injected? Is it a reference to the one held centrally by MVC (it's logical parent) or is it a brand new one created and configured solely for this class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

如果没结果 2024-09-22 09:33:29

注入到具有 IContainer 参数的构造函数中的容器与使用构造函数创建类实例的容器是同一容器。

Jeremy Miller 在他的 关于 NHibernate 和 StructureMap 的博客文章

难道您不能使用工厂模型来在需要时创建这些依赖项,以减少与容器的耦合吗?

您可以让您的模型采用 Func 作为参数,并使用 SM 的自动注入功能:

public class MyModel
{
   Func<IHeavyDep> _heavyFactory;
   public MyModel(Func<IHeavyDep> dependency)
   {
      _heavyFactory = dependency;
   }

   public void UsesHeavy()
   { 
      var heavy = _heavyFactory();
      heavy.DoMyStuff();
   }
}

The container injected into a constructor that has an IContainer parameter is the same container that is creating the instance of the class with the constructor.

Jeremy Miller has expressed this behaviour as "IContainer is injected into itself by default" in his blog post on NHibernate with StructureMap.

Couldn't you go with a factory model for creating those dependencies when needed in order to reduce your coupling to the container?

You could make your model take a Func as parameter and use SM's ability to autoinject those:

public class MyModel
{
   Func<IHeavyDep> _heavyFactory;
   public MyModel(Func<IHeavyDep> dependency)
   {
      _heavyFactory = dependency;
   }

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