I have a 3 layer solution with the following structure:
UI -> BLL <- DAL
The UI is an ASP.NET MVC application. Each controller requires BLL components on its constructor. And each BLL component requires DAL components on its constructor.
In the past I used StructureMap as the IoC container. And on its earlier versions, StructureMap used the ObjectFactory
class which was static. Because it was a static class I could use StructureMap on the MVC to replace the default ControllerFactory
and then another project where BLL and DAL configurations were made.
On newer StructureMap versions, ObjectFactory has been marked obsolete. I do understand that now I have to provide my own Container instance.
However, I don't have that chain happening without my projects being connected. Furthermore, if I add configurations to BLL and DAL to the MVC project, I will have to reference everything at the UI level which I would like to avoid.
What I think I have to do is to keep two different projects with StructureMap.
One inside the MVC project, responsible for creating controllers. However, I need to figure out a way to delegate BLL instances to the second container, which probably will keep where it is and knows how to create BLL and DAL (so BLL can be created).
The second one (to create BLL components) would look like this:
public static class BLLContainer
{
public static Container BuildServiceContainer()
{
return new Container(x =>
{
// This uses the Scan method to locate BLL and DAL
// interfaces and implementations.
x.AddRegistry(new DALRegistry());
});
}
}
My questions are:
Is it really possible to delegate object creation from my MVC application to the StructureMap container at the BLL level without having to reference additional (unneeded) projects?
If I'm returning a new instance of the container as the code above shows, this means I'm running the scanner for every request to the web server (StructureMap uses PerRequest as the default). How can I avoid that? I can't see how I'm going to prevent that other than going back to a Singleton.