i am trying to share some objects across multiple controllers. what is the best way to do this. i want to avoid singletons and i would like to inject these in if possible but with asp.net mvc you are not "newing" the controllers so any help would be appreciated.
+2
A:
Let me say, when I started with MVC, I had the same problem. Then I learned about IoC (Inversion of Control) containers and Dependency Injection, it is so amazing on how much these things allow you to do.
This project integrates Castle Windsor, NHibernate and ASP.NET MVC into one package. http://code.google.com/p/sharp-architecture/
If you want to do it yourself, what you can do is pick your favorite IoC container. There are some bindings out there for MVC or you can roll your own. If you want to do your own, you have to implement a IControllerFactory
and set MVC to use your factory. Here is mine.
public class ControllerFactory : IControllerFactory
{
private readonly IDependencyResolver _controllerResolver;
private RequestContext RequestContext { get; set; }
public ControllerFactory(IDependencyResolver controllerResolver)
{
_controllerResolver = controllerResolver;
}
public void ReleaseController(IController controller)
{
_controllerResolver.Release(controller);
var disposableController = controller as IDisposable;
if (disposableController != null)
disposableController.Dispose();
}
public IController CreateController(RequestContext requestContext, string controllerName)
{
Assert.IsNotNull(requestContext, "requestContext");
Assert.IsNotNullOrEmpty(controllerName, "controllerName");
RequestContext = requestContext;
try
{
var controllerInstance = _controllerResolver.Resolve<IController>(controllerName.ToLower() + "controller");
return controllerInstance;
}
catch(Exception ex)
{
throw new HttpException(404, ex.Message, ex);
}
}
}
Daniel A. White
2009-08-04 12:46:17