Search code examples
autofac

Autofac class with default parameter -> Override att runtime


I want to be able to resolve a class with default parameters sent to the constructor but i want to be able to override this when i specify a parameter.

Here is how i register:

builder.RegisterType<SearchService<WebPage>>().As<ISearchService<WebPage>>().WithParameter(
            new NamedParameter("solrUrl", ConfigurationManager.AppSettings["UrlWeb"])).SingleInstance();
        builder.RegisterType<SearchService<Document>>().As<ISearchService<Document>>().WithParameter(
            new NamedParameter("Url", ConfigurationManager.AppSettings["solrUrlDocs"])).SingleInstance();

To resolve i would like to be able to this:

_containerProvider.RequestLifetime.Resolve<ISearchService<WebPage>();

which works excellent but i also want to be able to do this:

_containerProvider.RequestLifetime.Resolve<ISearchService<WebPage>(new NamedParameter("Url", "some other url"));

which does not work .. So my question is if it is possible to register with a default parameter which i want to be able to override at runtime??


Solution

  • Below is a complete and simple example showing how to override at runtime, a NamedParameter configured at registration time.

    Important: The parameter name you use for the NamedParameter must match the parameter name in the constructor of the class you register and then resolve. In the example below, the parameter for Thing's constructor is name.

    using System;
    using Autofac;
    
    namespace BillAndBenConsole
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                var builder = new ContainerBuilder();
                builder.RegisterType<Thing>().WithParameter("name", "bill");
                var container = builder.Build();
    
                Console.WriteLine(container.Resolve<Thing>().Name);//Writes bill
                Console.WriteLine(container.Resolve<Thing>().Name);//Writes bill
                Console.WriteLine(container.Resolve<Thing>(new NamedParameter("name", "ben")).Name);//Writes ben
                Console.ReadLine();
            }
        }
    
        public class Thing
        {
            public string Name { get; set; }
    
            public Thing(string name)
            {
                Name = name;
            }
        }
    }