Windsor LifeStyle - Shared instance per Graph

前端 未结 2 382
抹茶落季
抹茶落季 2020-12-07 05:02

I have 2 types of ViewModel\'s

      public class ViewModelA 
      {
          IService service;
          private ViewModelB childViewModel; 

                  


        
2条回答
  •  青春惊慌失措
    2020-12-07 05:14

    You may be able to use Scoped Lifestyles. Here's an example of some unit tests that seem to do what you want:

    [Fact]
    public void VMsInSameScopeSharesService()
    {
        var container = new WindsorContainer();
        container.Register(Component.For().LifestyleTransient());
        container.Register(Component.For().LifestyleTransient());
        container.Register(Component
            .For().ImplementedBy().LifestyleScoped());
    
        using (container.BeginScope())
        {
            var a = container.Resolve();
    
            Assert.Equal(a.service, a.childViewModel.service);
        }
    }
    
    [Fact]
    public void VMsInDifferentScopesDoNotShareServices()
    {
        var container = new WindsorContainer();
        container.Register(Component.For().LifestyleTransient());
        container.Register(Component.For().LifestyleTransient());
        container.Register(Component
            .For().ImplementedBy().LifestyleScoped());
    
        IService service1;
        using (container.BeginScope())
        {
            var a = container.Resolve();
    
            service1 = a.service;
        }
        IService service2;
        using (container.BeginScope())
        {
            var a = container.Resolve();
    
            service2 = a.service;
        }
    
        Assert.NotEqual(service1, service2);
    }
    

    However, this is quite an exotic requirement, which makes me wonder why you want it to behave exactly like this, or if you couldn't structure your code in a way that would make this simpler.

提交回复
热议问题