问题
I'm ASP.NET MVC newbye and I'm learning and experimenting Enterprise design patterns: very interesting and helpful things indeed! But I keep missing something about the concept of disposing resources. To be more specific want to focus on the mechanism of controllerFactory which injects in the controller constructor an implementation of IFuncyRepository or IFuncyService or anyother kind of "resource" to be used in the controller (In my case I'm using StructureMap as IoC).
My question is WHERE / IF / HOW these injected resources get Disposed.
The book I'm following as guideline is ASP.NET Design Patterns and until now I can't get any explaination about this thing and also no clue becouse no class is structured implementing IDisposable. So looks like the resource disposing task gets done automagically somewhere (maybe in the IoC??). Since I can't understand this, I cannot be sure about the performance of my application which leads to very annoying doubts!
Thanks in advance to anyone will reply or share my concern ;)
回答1:
As a rule of thumb, the creator of a disposable object should also be the disposer of that same object. Thus, if you create an object graph from a custom IControllerFactory you should also use its ReleaseController for decommissioning.
Here's an example using Castle Windsor:
public class WindsorControllerFactory : DefaultControllerFactory
{
private readonly IWindsorContainer container;
public WindsorControllerFactory(IWindsorContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (IController)this.container.Resolve(controllerType);
}
public override void ReleaseController(IController controller)
{
this.container.Release(controller);
}
}
来源:https://stackoverflow.com/questions/6487028/explain-the-mysterious-world-of-ioc-and-automatic-dispose