Where to define Unity in N Tier Web Application?

Jul 3, 2010 at 10:56 PM
Edited Jul 3, 2010 at 11:46 PM

I have a 3 tier web project (2 Web interfaces, 1 BL and 1 DAL). I have configure Unity 2 inside both my global.asax like this:

public class Global : System.Web.HttpApplication, IContainerAccessor
{
//This is where i keep my Container instance.
private static IUnityContainer _container;

public static IUnityContainer Container
{
get { return _container; }
private set { _container = value; }
}
//This is define in the interface IContainerAccesor
IUnityContainer IContainerAccessor.Container
{
get { return Container; }
}
public void Application_Start(object sender, EventArgs e)
{
//here is where i instantiate the container
IUnityContainer container = new UnityContainer();
container.AddExtension(new EnterpriseLibraryCoreExtension());
container.LoadConfiguration();
Container = container;
}
}
}

//This is the interface
public interface IContainerAccessor
{
IUnityContainer Container { get; }
}

Everything works fine, even wrote some generics to extend my pages, mastepages and usercontrols to get everything injected in there. The problem comes with the BL classes that need to create object and have no reference to the container itself.

I am looking for an elegant solution to my problem and i have found only one. Making my unity a Singleton and accesing it from layers. But i found my self in a problem when testing my objects, since they make reference to the IContainer.

Another idea, is to have all my objects having an instance of IContainer, but i dont consider this to be a good solution, seems (have not tried it)

i want ot add a few links that i have found with a similar question, that i think will bring some light

http://stackoverflow.com/questions/2386487/is-it-better-to-create-a-singleton-to-access-unity-container-or-pass-it-through-t

http://stackoverflow.com/questions/1943576/is-there-a-pattern-for-initializing-objects-created-wth-a-di-container/1945023#1945023

Also found this post that explains my exact problem but gives no solutiuon. I consider my BL and DAL to be APIs, consume by other developers.

http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx

Thanks Pablo Szittyay