Enterprise Library Lifetime Managers

Update: fixed a bug in the attached code.

Enterprise Library comes with several lifetime manager, which you can use to control how your objects are stored and retrieved. The available lifetime managers are:

  • ExternallyControlledLifetimeManager: stores a weak reference to objects which are created elsewhere
  • PerThreadLifetimeManager: stores objects in a thread static dictionary)
  • ContainerControlledLifetimeManager (the default): stores objects in the Unity container
  • TransientLifetimeManager: does not store objects, create a new one every time it is requested

In web applications, we may need additional options, for example:

  • Store objects in the current session
  • Store objects in the current request
  • Store objects in the current application

So, I wrote three new lifetime managers, for each of these requirements: WebSessionLifetimeManager, WebRequestLifetimeManager and WebApplicationLifetimeManager. Another possibility would be a pooled lifetime manager, which will be the subject for a future post.

                             

3 Comments

  • Hi, Brett!

    Yes, you are right: there was a bug in my code. I have uploaded a new version.
    Regarding your problem, the only way to do this is by using a module that hooks to the EndRequest event, and have the request lifetime manager register objects on this module. I have included the source code, have a look.
    What happens is that objects were only removed when the lifetime manager was garbage collected.
    Regarding session and application, there other problems: you cannot hook the SessionEnd and ApplicationEnd events from a module, so the code would have to go to Global.asax.cs. It is better if your objects do not need or rely of any disposing mechanism.

    Regards,

    Ricardo

  • The problem is that often the objects do need to implement IDisposable and do need to be disposed of during their lifetime.

    Better to not try to do this with a custom lifetime manager but with child containers with disposable objects that can be disposed of on each request for proper cleanup.

    Regards,

    Dave

  • Hi, Dave, thanks for your comment! It's an honor to have a guy like you post a comment on a blog of a guy like me! :-)
    I will look more into it... My solution allows for proper termination of objects through the IDisposable interface at the end of requests, but, sadly, not at the end of sessions. I will try to reproduce it with child containers.
    Best regards,
    Ricardo

Comments have been disabled for this content.