Search code examples
c#autofac

how to pass parameters on resolve time in autofac


I write following register type in autofac:

 builder.RegisterType<NoteBookContext>()
        .As<DbContext>()
        .WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));

In fact I write this code for injecting NoteBookContext with a connectionstring parameter. (ie : new NoteBookContext(string connectionstring))

Now , How can I Pass value of parameter at runtime?


Solution

  • The WithParameter method has a overload that accept delegate for dynamic instanciation.

    The first argument is a predicate selecting the parameter to set whereas the second is the argument value provider :

    builder.RegisterType<NoteBookContext>()
           .As<DbContext>()
           .WithParameter((pi, c) => pi.Name == "connectionstring", 
                          (pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString);
    

    See Passing Parameters to Register from Autofac documentation for more detail.