Nancy icon indicating copy to clipboard operation
Nancy copied to clipboard

Nancy disposes of specific instance dependencies on it's own

Open Demiu opened this issue 5 years ago • 0 comments

Description

If you register a specific instance of an object during Bootstrapper's ConfigureRequestContainer it will dispose of said instance when a new NancyHost is created using that bootstrapper and on subsequent requests going through that host.

Steps to Reproduce

public class UnmanagedClass : IDisposable
    {
        bool disposed;

        public UnmanagedClass()
        {
            disposed = false;
            Console.WriteLine("Created");
        }

        public void Dispose()
        {
            if (disposed) {
                Console.WriteLine("Double dispose");
            } else {
                Console.WriteLine("Fist dispose");
                disposed = true;
            }
        }

        public string GetSomeData()
        {
            if (disposed) {
                return "I was disposed!";
            } else {
                return "Here, some data";
            }
        }
    }

    class CustomBootstrapper : DefaultNancyBootstrapper
    {
        private readonly UnmanagedClass dependency;

        public CustomBootstrapper(UnmanagedClass inDep) : base()
        {
            dependency = inDep;
        }

        protected override void ConfigureRequestContainer(TinyIoCContainer container, NancyContext context)
        {
            base.ConfigureRequestContainer(container, context);

            // Now this specific instance of UnmanagedClass will be passed to modules
            container.Register(dependency);
        }
    }

    public class UserModule : NancyModule
    {
        // A module doesnt even need to depend on a UnmanagedClass
        public UserModule()
        {
            Get(@"/", _ => "l");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            // an instance of managed class created "somewhere else"
            var dependencyInstance = new UnmanagedClass();

            // Host is made from a bootstrapper, immediately disposes
            var bootstrapper = new CustomBootstrapper(dependencyInstance);
            var host = new NancyHost(bootstrapper, new Uri("http://localhost:6999")); // dependencyInstance is disposed
            host.Start();

            Console.ReadKey();
            // and regular disposes here
        }
    }

Just prints out "Create" and immediately "First dispose"

  • Nancy version: 2.0.0
  • Nancy host:
    • [x] Nancy.Hosting.Self
  • Other Nancy packages and versions: master in this repo
  • Environment (Operating system, version and so on):
  • .NET Framework version: Core 2.0 and Framework 4.6.1, but should apply to everything

Demiu avatar Mar 11 '20 17:03 Demiu