c# - StructureMap 认为它必须注入(inject)构造函数并抛出异常

标签 c# asp.net asp.net-mvc structuremap structuremap3

我在我的应用程序中使用 StructureMap 和 ASP.Net Identity。当我的 Application_Start

中有这一行时
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());

这是StructureMapControllerFactory:

public class StructureMapControllerFactory : DefaultControllerFactory
{
    protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
    {
        if (controllerType == null && requestContext.HttpContext.Request.Url != null)
            throw new InvalidOperationException(string.Format("Page not found: {0}",
                requestContext.HttpContext.Request.Url.AbsoluteUri.ToString(CultureInfo.InvariantCulture)));
        return ObjectFactory.GetInstance(controllerType) as Controller;
    }
}

return ObjectFactory.GetInstance(controllerType) as Controller; 抛出一个 StructureMapConfigurationException 异常说:

No default Instance is registered and cannot be automatically determined for type 'IUserStore<Person>'

但是如果我删除 ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()); 行一切正常所以这是 StructureMap 的问题而不是我的代码。

最佳答案

我认为异常(exception)很明显。这可能与 Identity 模板中的 AccountController 有关,它带有 2 个构造函数。

StructureMap 将使用 most greediest constructor默认情况下。该模板带有 2 个构造函数,一个默认构造函数和一个带有 ApplicationUserManager 的构造函数对象。

在没有 StructureMap 的情况下,默认构造函数被调用,ApplicationUserManager 将使用 service locator anti pattern 解析.

StructureMap 现在必须创建 ApplicationUserManager因为这是一个具体的类型,所以它会尝试。如果它是一个抽象的,它会在那里抛出异常。 ApplicationUserManager但是有一个构造函数需要 IUserStore<Person> .因为这是一个抽象并且容器没有注册这种类型,所以 StructureMap 无法为您创建类型。

要解决这个问题,您应该删除默认构造函数并注册 ApplicationUserManager 和相关服务,这些服务至少是实现 IUserStore 的某个组件。

编辑: 虽然您在评论中提到的解决方案可能有效,但这不是可取的解决方案,因为:

  1. Having multiple constructors is an anti-pattern
  2. 您现在正在使用服务定位器反模式来解析 ApplicationUserManager来自 HttpContext

VS2013 附带的模板需要一些工作才能与依赖注入(inject)一起使用。这将花费一些时间。好消息是,这是可能且可行的,并且会大大提高您对 Owin 的了解。 , Asp.Net Identity ,依赖注入(inject)和SOLID design .

有几篇博客介绍如何开始重构模板以使用依赖注入(inject)。你可以读到那个 herehere

关于c# - StructureMap 认为它必须注入(inject)构造函数并抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29244098/

相关文章:

c# - 自定义 resx 框架 Visual Studio 2010

c# - Signalr 将 IHubContext 转换为实际的 Hub

asp.net - 将文件从 Asp.Net 写入 Azure 文件存储失败

c# - 无法将字符串隐式转换为文本框

asp.net - ASP MVC 将 Controller 的所有请求路由到 Index 操作?

c# - 指定服务器端代码的相对路径

c# - C# MongoClient 是否可以在不首先序列化为 .NET 类型的情况下用于返回有效的 JSON?

c# - 删除 Azure Keyvault 上的 secret 不起作用

asp.net - 单个按钮中的两个验证组,无需客户端单击事件

asp.net-mvc - 未选择值的 DropDownList