2012-12-17 138 views
3

是否可以在注册表中注册接口,然后“重新注册”它以覆盖首次注册?结构图 - 覆盖注册

即:

For<ISomeInterface>().Use<SomeClass>(); 
For<ISomeInterface>().Use<SomeClassExtension>(); 

我想在这里上运行什么是我的对象工厂返回SomeClassExtension当我问ISomeInterface

在此先感谢!

回答

2

好消息,我发现是的。这一切都取决于注册表规则添加到对象工厂容器的顺序。因此,如果您像我一样使用多个注册表类,则需要找到一种方法来优先将它们添加到容器中。

换句话说,而不是使用它得到错误的顺序所有Registry.LookForRegistries(),试图找到所有Registry文件,将它们在你希望的顺序和手动添加的对象工厂容器:

ObjectFactory.Container.Configure(x => x.AddRegistry(registry)); 

这样,您就可以完全控制所需的规则。

希望它能帮助:)

1

我只是想我的解决方案添加到这个问题时,我需要重写注册表的某些部分在我SpecFlow测试。

我确实在我的搜索中很早就发现了这个线程,但它并没有真正帮助我找到解决方案,所以我希望它能帮助你。

我的问题是“StoreRegistry”(由应用程序使用)中的“DataContext”使用“HybridHttpOrThreadLocalScoped”,我需要它在我的测试中是“瞬态”。

The code looked like this: 
[Binding] 
public class MySpecFlowContext 
{  
... 
    [BeforeFeature] 
    private static void InitializeObjectFactories() 
    { 
     ObjectFactory.Initialize(x => 
     { 
      x.AddRegistry<StoreRegistry>(); 
      x.AddRegistry<CommonRegistry>(); 
     }); 
    } 
} 

要重写范围设置,您需要在注册中明确设置它。 并且覆盖需要低于被覆盖的内容

The working code looks like this: 
[Binding] 
public class MySpecFlowContext 
{  
... 
    [BeforeFeature] 
    private static void InitializeObjectFactories() 
    { 
     ObjectFactory.Initialize(x => 
     { 
      x.AddRegistry<StoreRegistry>(); 
      x.AddRegistry<CommonRegistry>(); 
      x.AddRegistry<RegistryOverrideForTest>(); 
     }); 
    }  

    class RegistryOverrideForTest : Registry 
    { 
     public RegistryOverrideForTest() 
     { 
      //NOTE: type of scope is needed when overriding the registered classes/interfaces, when leaving it empty the scope will be what was registered originally, f ex "HybridHttpOrThreadLocalScoped" in my case. 
      For<DataContext>() 
       .Transient() 
       .Use<DataContext>() 
       .Ctor<string>("connection").Is(ConnectionBuilder.GetConnectionString()); 
     } 
    } 
}