Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass parameters on resolve time in autofac

Tags:

c#

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?

like image 304
mina morsali Avatar asked Apr 25 '16 08:04

mina morsali


2 Answers

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.

like image 150
Cyril Durand Avatar answered Sep 23 '22 19:09

Cyril Durand


In order to pass the connection string value while resolving, we first need to pass the delegate of the constructor into the Register method, and then pass the value of connection string with the NamedParameter into the Resolve method.

For example:

ContainerBuilder builder = new ContainerBuilder();

builder.Register((pi, c) => new NoteBookContext(pi.Named<string>("connectionstring")))
            .As<DbContext>();

Now, on resolve time, we can assign to the resolved DBContext the conncetionstring value of Consts.MyConnectionString:

IContainer container = builder.Build();

NoteBookContext noteBookContext = container.Resolve<DbContext>(
    new NamedParameter(
        "connectionstring", Consts.MyConnectionString
    )
);
like image 37
Shahar Shokrani Avatar answered Sep 24 '22 19:09

Shahar Shokrani