Can I use the exemplary lifestyle at Windsor Castle without going around the container?

In general, it is generally accepted that passing the IoC container around your application and using it as a service locator is bad practice.

I prefer to use the container only in the composite root of my application and, as a rule, makes one call to Resolve () - resolving the top-level object in my application and responding to the container to introduce dependencies to classes below the object graph.

Windsor Castle recently added a lifestyle in which you can call container.BeginScope () in the using block. From within this block, β€œuse”, allowing a component that has been registered in the cloud lifestyle, will always return the same instance throughout the entire β€œuse” of the block.

container.Register(Component.For<A>().LifestyleScoped()); using (container.BeginScope()) { var a1 = container.Resolve<A>(); var a2 = container.Resolve<A>(); Assert.AreSame(a1, a2); } 

Question: Given that BeginScope () is an extension method in a container, I don’t see how an exemplary lifestyle can be used in an application if the container is not passed (which I really do not want to do). Does anyone have examples of where / how to use an exemplary lifestyle?

Thanks,

Tom

+7
source share
1 answer

I think the usage will usually be inside the factory, which usually opens to see the container. Think of a web application: in a sense, every controller call in an MVC application or β€œpage” launches a semi-independent program. It is unreasonable for this "program" to resolve its own dependencies. That is, each controller call must resolve its dependencies using the container.

As part of a specific web request or a TCP request or user session, you might want the container to allow objects in different ways. This is a way for you to do this at one of your own plants. As with all IoC applications, you must be careful not to abuse it so that the business logic gets into your registration code.

+7
source

All Articles