StructureMap 错误 - 没有注册默认实例

StructureMap error - no default instance is registered

我有一个使用 StructureMap IoC 容器的控制台演示应用程序。 demo中所有的接口和实现都在一个文件中,在一个项目中,扫描注册表如下所示:

public class ConsoleRegistry : Registry
{
    public ConsoleRegistry()
    {
        Scan(scan =>
        {
            scan.TheCallingAssembly();
            scan.WithDefaultConventions();
        });
    }
}

并且演示使用约定 ISomethingSomething 因此 StructureMap 可以自动找到接口的实现。

现在,当我将它移动到一个真实的项目时,那里有一个 UI 项目和一个业务项目 。我保持 ISomethingSomething 的约定,但是当我尝试 运行 我的单元测试项目中的集成测试时,我收到以下错误消息。

Message: Test method AbcCompany.Tests.IntegrationTestsForTasks.Get_something_test threw exception: StructureMap.StructureMapConfigurationException: No default Instance is registered and cannot be automatically determined for type 'AbcCompany.DomainLayer.ISomething'

There is no configuration specified for AbcCompany.DomainLayer.ISomething 1.) Container.GetInstance()

如果我将注册表更改为以下它会起作用:

class ScanningRegistry : Registry
{
    public ScanningRegistry()
    {
        this.For<ISomething>().Use<Something>();

        this.Policies.SetAllProperties(y => y.WithAnyTypeFromNamespaceContainingType<Something>());
    }
}

但是,如果我坚持使用标准命名约定,StructureMap 会为我找到所有接口和实现,而无需指定它们,我喜欢这样。

您只是在扫描 TheCallingAssembly。当您的应用程序运行时,调用程序集就是您的应用程序。当测试运行器运行时,调用程序集就是测试运行器。

为使其可靠,您应该手动指定每个程序集:

Scan(scan =>
{
    scan.Assembly(typeof(SomeTypeFromAssembly1).Assembly);
    scan.Assembly(typeof(SomeTypeFromAssembly2).Assembly);
    scan.WithDefaultConventions();
 });

或者您应该使用 the scanning documentation 中的其他方法之一按目录名称指定程序集。