【问题标题】:StructureMap with MVC and multiple layers具有 MVC 和多层的 StructureMap
【发布时间】:2016-06-09 07:45:38
【问题描述】:

我正在使用 StructureMap.MVC5 并且有以下项目和类:

Web
    HomeController(PageService pageService)
Services
    PageService(IPageRepository pageRepository)
Repositories
    PageRepository : IPageRepository
IRepositories
    IPageRepository

使用 StructureMap.MVC5 的默认实现,它会自动将 PageService 解析为我的 HomeController,但不会将 PageRepository 解析为我的 PageService。这给了我一个例外:No parameterless constructor defined for this object.

这可以通过在 DefaultRegistry 中添加一行来解决:

For<IPageRepository>().Use<PageRepository>();

但显然我宁愿让 StructureMap 自动解决这个问题。有没有办法做到这一点?

这是 DefaultRegistry 的样子:

public DefaultRegistry()
{
    Scan(scan =>
    {
        scan.TheCallingAssembly();
        scan.WithDefaultConventions();
        scan.With(new ControllerConvention());
    });
}

【问题讨论】:

    标签: asp.net .net asp.net-mvc dependency-injection structuremap


    【解决方案1】:

    您的存储库没有被自动解析的原因是因为它位于另一个程序集中,因为您的服务在您的控制器中被引用,这意味着它通过TheCallingAssembly 调用得到解析。

    要告诉 StructureMap 加载您的存储库,您必须明确告诉它要扫描哪个程序集:

    scan.AssemblyContainingType<IPageRepository>();
    

    指定的类型不必是 IPageRepository 类型,只要是存储库程序集中的某个类型,以便 StructureMap 知道在哪里查找。

    现在您的存储库程序集中的任何类型都应该被自动解析。

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2011-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2010-10-30
      相关资源
      最近更新 更多