如何在不处理根容器的情况下处理(或仅重置)Facade?

时间:2019-02-13 22:16:02

标签: c# dryioc prism-7

我在选项卡式模块化应用程序中使用带有Prism WPF的DryIoc 3.0.2:每个选项卡(如Chrome选项卡-支持撕裂)都有自己的容器,授权的UserContext和一组共享的Prism模块,尤其是初始化为标签的容器(如所述的here)。

需要在保持根依赖关系的情况下正确(且不久)拆分子容器。任何选项卡都可能在处理完所有资源后随时关闭。

测试项目:

    public interface IStorage { }

    public class Storage : IStorage { }

    public class UserContext
    {
        public UserContext(IStorage storage)
        {

        }
    }

测试:

[Test] // Failed.
public void TestMultipleFacades()
{
    var container = new Container();

    container.Register<IStorage, Storage>(Reuse.Singleton);
    // ..Some other registrations here.

    // Container for isolated tab with its own context.
    var local1 = container.CreateFacade();
        local1.Register<UserContext>(Reuse.Singleton);

    // For another tab.
    var local2 = container.CreateFacade();
        local2.Register<UserContext>(Reuse.Singleton);

    Assert.AreNotEqual(local1.Resolve<UserContext>(), local2.Resolve<UserContext>());

    // Closing first tab.
    local1.Dispose(); // Free all local1 data with its own singletones!

    // Opening a new tab.
    //
    // Throws DryIoc.ContainerException:
    // Container is disposed and should not be used: Container is disposed.
    var local3 = container.CreateFacade();
}

[Test] // Passed!
public void TestMultipleContainers()
{
    var rootContainer = new Container();

    rootContainer.Register<IStorage, Storage>(Reuse.Singleton);
    // ..Some other registrations here.

    var local1 = new Container(rootContainer.Rules);
        // Direct re-registration (hard to enumerate all of rootContainer).
        local1.UseInstance(rootContainer.Resolve<IStorage>());
        local1.Register<UserContext>(Reuse.Singleton);

    var local2 = new Container(rootContainer.Rules);
        local2.UseInstance(rootContainer.Resolve<IStorage>());
        local2.Register<UserContext>(Reuse.Singleton);

    Assert.AreNotEqual(local1.Resolve<UserContext>(), local2.Resolve<UserContext>());

    local1.Dispose(); // Free all local1 data with its own singletones!

    var local3 = new Container(rootContainer.Rules);
}

[Test]
public void TestMultipleScopes()
{
    var rootContainer = new Container();

    rootContainer.Register<IStorage, Storage>(Reuse.Singleton);
    // ..Some other registrations here.

    var local1 = (IContainer) rootContainer.OpenScope();
        local1.Register<UserContext>(Reuse.Singleton);

    var local2 = (IContainer) rootContainer.OpenScope();
        local2.Register<UserContext>(Reuse.Singleton);

    Assert.AreNotEqual(local1.Resolve<UserContext>(), local2.Resolve<UserContext>());

    local1.Dispose(); // Free all local1 data with its own singletones!

    var local3 = (IContainer) rootContainer.OpenScope();
}

1 个答案:

答案 0 :(得分:0)

我建议创建一个标签为question和DryIoc repo(我是所有者)的问题,并将包含测试的PR添加到DryIoc.IssuesTests项目中。通常,因为您已经有可以以这种方式运行和检查更快的测试。此外,您还可以根据最新版本自行检查测试。