具有 MVC 和多层的 StructureMap

StructureMap with MVC and multiple layers

我正在使用 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 自动解决这个问题。有办法实现吗?

这是默认注册表的样子:

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

你的存储库没有被自动解析的原因是因为它在另一个程序集中,当你的服务在你的控制器中被引用时,这意味着它被 TheCallingAssembly 调用解析。

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

scan.AssemblyContainingType<IPageRepository>();

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

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