相关疑难解决方法(0)

创建单例来访问统一容器或通过应用程序传递它是否更好?

我正在使用IoC框架,我选择使用Unity.我还没有完全理解的一件事是如何更深入地解析应用程序中的对象.我怀疑我当时还没有灯泡可以说清楚.

因此,我尝试在psuedo'ish代码中执行以下操作

void Workflow(IUnityContatiner contatiner, XPathNavigator someXml)
{
   testSuiteParser = container.Resolve<ITestSuiteParser>
   TestSuite testSuite = testSuiteParser.Parse(SomeXml) 
   // Do some mind blowing stuff here
}
Run Code Online (Sandbox Code Playgroud)

所以testSuiteParser.Parse执行以下操作

TestSuite Parse(XPathNavigator someXml)
{
    TestStuite testSuite = ??? // I want to get this from my Unity Container
    List<XPathNavigator> aListOfNodes = DoSomeThingToGetNodes(someXml)

    foreach (XPathNavigator blah in aListOfNodes)
    {
        //EDIT I want to get this from my Unity Container
        TestCase testCase = new TestCase() 
        testSuite.TestCase.Add(testCase);
    } 
}
Run Code Online (Sandbox Code Playgroud)

我可以看到三个选项:

  1. 创建一个Singleton来存储我可以在任何地方访问的Unity容器.我真的不喜欢这种方法.添加这样的依赖项来使用依赖注入框架似乎有点奇怪.
  2. 将IUnityContainer传递给我的TestSuiteParser类及其中的每个子类(假设它是n级深度或实际上大约3级深度).在任何地方传递IUnityContainer只是看起来很奇怪.我可能只需要克服这一点.
  3. 在正确的方式上使用Unity的灯泡时刻.希望有人可以帮助轻弹开关.

[编辑]我不清楚的一件事是我想为foreach语句的每次迭代创建一个新的测试用例实例.上面的示例需要解析测试套件配置并填充测试用例对象的集合

c# ioc-container unity-container

49
推荐指数
2
解决办法
2万
查看次数

标签 统计

c# ×1

ioc-container ×1

unity-container ×1