StructureMap 依赖解析 : Manually get instance from ActionFilter

标签 structuremap asp.net-web-api

我正在尝试使用 StructureMap 来遵循本教程:http://iridescence.no/post/Constructor-Injection-for-ASPNET-MVC-Action-Filters.aspx

我试图找出与此行等效的 StructureMap:

var container = (ICanResolveDependencies) HttpContext.Current.ApplicationInstance;

我想找回容器,这样我就可以手动解决那里的依赖关系。

这就是我在 global.asax 中设置 dependencyresolver 的方式

            GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
            new StructureMapDependencyResolver(container));

最佳答案

您可以只在操作过滤器的构造函数中要求 IContainer 依赖项。如果 StructureMap 没有自动注册它,您可以通过以下方式注册:

For<IContainer>().Use<Container>();

编辑

选项 1:您不能使用类似以下内容吗:

GlobalConfiguration.Configuration.ServiceResolver.GetService(...)
// or (not sure what would be the right syntax)
GlobalConfiguration.Configuration.ServiceResolver.Current.GetService(...)

一旦设置了当前的服务解析器,就必须有某种方法来检索它。

选项 2:使用常规 MVC,您可以像这样获取当前解析器:

DependencyResolver.Current

并像这样使用它:

DependencyResolver.Current.GetService()

看起来WebAPI没有使用DependencyResolver,但是根据this blog post ,你可以这样设置:

DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
// this override is needed because WebAPI is not using DependencyResolver to build controllers
GlobalConfiguration.Configuration.ServiceResolver.SetResolver(
    DependencyResolver.Current.GetService,
    DependencyResolver.Current.GetServices);

现在尝试使用操作过滤器中的DependencyResolver.Current

选项 3:直接使用 ObjectFactory.GetInstance - 可能不是 MVC 项目中的最佳主意,因为它应该已经封装在 IDependencyResolver 实例中。

关于StructureMap 依赖解析 : Manually get instance from ActionFilter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11164281/

相关文章:

c# - StructureMap 在 HttpContext 上抛出 ArgumentNullException

asp.net-mvc - 如何为启用延迟加载的 MVC 应用程序应用事务隔离级别?

c# - 如何在两种不同情况下使用 StructureMap 获取通用对象的实例?

c# - 如何使用 Azure 媒体服务生成 Sprite 缩略图

.net - WCF 与 REST API?

c# - 如何检索给定 HttpRequestMessage 的路由模板变量?

c# - 无法使用 StructureMap 从私有(private)或内部构造函数调用 BuildUp

c# - 使用 Structure Map 替换泛型类型参数中的抽象类型

c# - 在iis服务器上从web api运行exe文件不起作用

asp.net-mvc-4 - 如何创建 ASP.NET Web API URL?