简体   繁体   中英

When building my Autofac container, how do I include previously registered types as parameters in other registered types?

Consider the following:

        public static IContainer Configure()
        {
            var builder = new ContainerBuilder();

            // Register a named HttpClient instance as a singleton.
            builder.Register(_ =>
            {
                var client = new HttpClient
                {
                    MaxResponseContentBufferSize = int.MaxValue,
                    Timeout = TimeSpan.FromMinutes(50)
                };

                client.DefaultRequestHeaders.Add("Connection", "Keep-Alive");
                client.DefaultRequestHeaders.Add("Keep-Alive", "3600");
                return client;
            })
            .SingleInstance();

            builder.Register(l => new RandomObject(new HttpClient, "randomString")).As<IRandomObject>();


            return builder.Build();
        }

When registering my RandomObject , how do I replace that new HttpClient instance in my previously registered HttpClient ? Failing that, is there a way new-up the HttpClient parameter so that it has the same settings as the previously registered one?

I think you should use resolve method for that

builder.Register(l => new RandomObject(l.Resolve<HttpClient>(), "randomString").As<IRandomObject>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM