I have 2 types of ViewModel\'s
public class ViewModelA
{
IService service;
private ViewModelB childViewModel;
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.