How to use Autofac to resolve instance per request dependencies for types in a child lifetime scope created by Nancy

后端 未结 1 1595
鱼传尺愫
鱼传尺愫 2021-02-10 15:57

We have several applications hosted in Windows services that self host a Nancy endpoint in order to expose instrumentation about the operation of the applications.

We u

相关标签:
1条回答
  • 2021-02-10 16:37

    Autofac should automatically resolve instances from "parent" lifetimes. If you configure your registrations using InstancePerRequest, Autofac will register these services with a special lifetime tag, MatchingScopeLifetimeTags.RequestLifetimeScopeTag, so it can be resolved in the correct scope later.

    This means that there's no need to use the Nancy bootstrapper's ConfigureRequestContainer method to do request-scoped registrations. You've already done it! As long as Nancy creates the request lifetime using the same tag used in InstancePerRequest (this is done by default as of Nancy 1.1), the services should be resolved correctly.

    Example:

    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
    
            // Do request-scoped registrations using InstancePerRequest...
    
            var container = builder.Build();
    
            // Pass the pre-built container to the bootstrapper
            var bootstrapper = new MyAwesomeNancyBootstrapper(container);
    
            app.UseNancy(options => options.Bootstrapper = bootstrapper);
        }
    }
    
    public class MyAwesomeNancyBootstrapper : AutofacNancyBootstrapper
    {
        private readonly ILifetimeScope _lifetimeScope;
    
        public MyAwesomeNancyBootstrapper(ILifetimeScope lifetimeScope)
        {
            _lifetimeScope = lifetimeScope;
        }
    
        protected override ILifetimeScope GetApplicationContainer()
        {
            return _lifetimeScope; // Tell Nancy you've got a container ready to go ;)
        }
    }
    

    This setup should be enough (As of Nancy 1.1. In earlier versions you have to also override the CreateRequestContainer method and pass the request lifetime tag when creating the request lifetime scope).

    EDIT: I put together an example for you at https://github.com/khellang/Nancy.AutofacExample

    0 讨论(0)
提交回复
热议问题