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?
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.
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
)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With