Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ASP.NET lifetime provider doesn't dispose #53

Open
Daniel15 opened this issue Mar 20, 2014 · 1 comment
Open

ASP.NET lifetime provider doesn't dispose #53

Daniel15 opened this issue Mar 20, 2014 · 1 comment

Comments

@Daniel15
Copy link

Unless I'm missing something, it looks like the ASP.NET lifetime provider does not dispose registered components at the end of a request. All registered components that are IDisposable should be disposed at the end of the request.

@Daniel15
Copy link
Author

Here's how I fixed it on mine:

1 - Add code to dispose all created objects in the HTTP context. I just stuck this in TinyIoCAspNetExtensions:

private const string PREFIX = "TinyIoC.HttpContext.";
...
public static void DisposeAll()
{
    var items = HttpContext.Current.Items;
    var disposableItems = items.Keys.OfType<string>()
        .Where(key => key.StartsWith(PREFIX))
        .Select(key => items[key])
        .Where(item => item is IDisposable);

    foreach (var item in disposableItems)
    {
        ((IDisposable)item).Dispose();
    }
}

2 - Call it at the end of the request. My init code is in WebActivator but you could just stick it in Application_EndRequest in Global.asax.cs:

using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using TinyIoC;

[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(MyApp.Initializer), "Initialize")]

namespace MyApp
{
    internal static class Initializer
    {
        public static void Initialize()
        {
            InitializeIoC();
            DynamicModuleUtility.RegisterModule(typeof(IocPerRequestDisposal));
        }

        internal class IocPerRequestDisposal : IHttpModule
        {
            public void Init(HttpApplication context)
            {
                context.EndRequest += (sender, args) => HttpContextLifetimeProvider.DisposeAll();
            }
            public void Dispose() { }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant