I am fiddling with LightInject to try and set up a IoC solution containing a Domain proj, a Infrastructure proj, a MVC proj, and a DependencyResolution proj. Infrastructure, MVC, and DependencyResolution references Domain. MVC references DependencyResolution and DependencyResolution references LightInject.
The idea is that DependencyResolution registers all necessary dependencies at app startup. It has no knowledge of the controllers in the MVC proj at this time. Instead I set up a fallback routine to catch all unknown MVC Controller classes. In the fallback routine I then register the MVC Controller and return it. By doing this I expect this code to only be run one time, since it is only by the first hit the MVC Controller is not registered yet. But this is not the case. Instead I get a StackOverflowException because the fallback routine is hit every time the MVC Controller is asked for even though it was registered the first time.
So the question is why this happens? Is this expected behaviour and if so, why is that and how to get around it?
Edit: Here is the source code below.
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(DependencyResolution.App_Start.WebCommon), "Start")]
namespace DependencyResolution.App_Start
{
static class WebCommon
{
private static readonly TempProject.LightInject.ServiceContainer _serviceContainer = new TempProject.LightInject.ServiceContainer();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
var container = _serviceContainer;
RegisterServices(container);
Domain.ServiceLocator.SetServiceLocator(() => new ServiceLocator(container));
}
/// <summary>
/// Load your modules or register your services here!
/// </summary>
/// <param name="container">The IoC container.</param>
private static void RegisterServices(TempProject.LightInject.ServiceContainer container)
{
System.Func<TempProject.LightInject.ServiceRequest, object> fallback = request =>
{
var serviceType = request.ServiceType;
container.Register(serviceType, serviceType);
return container.GetInstance(serviceType);
};
container.RegisterFallback((type, s) => type.Name.EndsWith("Controller"), request => fallback(request));
var assembly = typeof(Domain.IServiceLocator).Assembly;
container.RegisterAssembly(assembly);
}
}
}