[TestFixture]
public sealed class BoundedLifestyleTests
{
class ViewModel
{
public IService[] Services { get; set; }
}
public interface IService { }
class NeutralStrategy : IService { }
class SpecializedStrategy : IService { }
/// <summary>
/// I have some IService implementations, where the are either are neutral (could be used in any context)
/// or are specialized (should be resolved only in ViewModel).
/// I would like to implement that requirement with LifestyleBoundTo which looks promising.
/// </summary>
[Test]
public void Test()
{
var container = new WindsorContainer();
container.Kernel.Resolver.AddSubResolver(new CollectionResolver(container.Kernel, true));
container.Register(
Component.For<IService>().ImplementedBy<NeutralStrategy>(),
Component.For<ViewModel>(),
Component.For<IService>().ImplementedBy<SpecializedStrategy>().LifestyleBoundTo<ViewModel>());
// ViewModel has neutral and specialized strategies resolved.
var viewModel = container.Resolve<ViewModel>();
Assert.That(viewModel.Services.Select(o => o.GetType()), Is.EquivalentTo(new[] { typeof(NeutralStrategy), typeof(SpecializedStrategy) }));
// Outside of a graph bound to ViewModel, we still should be able to resolve neutral strategy.
var neutralStrategies = container.ResolveAll<IService>();
Assert.That(neutralStrategies.Select(o => o.GetType()), Is.EquivalentTo(new[] { typeof(NeutralStrategy) }));
}
}