Question

The ASP.NET MVC has many components. Controllers, actions, static classes, ApiControllers, Filters, RouteTables, BundleTables, Factories, et cetera along with access modifiers to controller scope.

If we instantiate an object or access a static property within any of these, how do we determine the object's, class's, or member's scope and lifetime. Take this example for instance:

public static class MyHelper
{
    public static object MyProperty { get; set; }
    public static Func<object> MyPropertyFactory { get; set; }

    static MyHelper()
    {
        MyProperty = new object();
        MyPropertyFactory = () => new object();
    }
}
public class MyController : ApiController
{
    public object MyAppProperty { get; set; }
    public object MyRequestProperty { get; set; }

    public MyController()
    {
        MyAppProperty = MyHelper.MyProperty;
        MyRequestProperty = MyHelper.MyPropertyFactory;
    }

    public object MyAction()
    {
        var MyActionObject = new object();
        return MyActionObject;
    }
}

I find the lifetime and scope of the different objects and static class properties difficult to parse. This gets my into threading and other problems.

Other than analysis and experience, is there a generally process for determining this? Another more answerable question is: "What is the lifetime and scope of each of the following and why?

  • MyHelper
  • MyHelper.MyProperty
  • MyHelper.MyPropertyFactory
  • MyController
  • MyController.MyAppProperty
  • MyController.MyRequestProperty
  • MyController.MyAction.MyActionObject
Was it helpful?

Solution

All static properties have AppDomain lifetime (from first usage to shutdown/restart).

Others (Controllers, models and views) - request lifetime (created during request, eligible for GC after end of that request).

OTHER TIPS

May I suggest to use Dependency Injection container. Your problem with lifetime-scoping will go away, because the container will manage all of these for you.

Instead of static initiations and messing about with functions-factories you'll do:

private readonly IService service;
private readonly IOtherService otherService;

public MyController(IService service, IOtherService)
{
    this.service = service;
    this.otherService = otherService;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top