mina morsali
mina morsali

Reputation: 778

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?

Upvotes: 7

Views: 9300

Answers (3)

workabyte
workabyte

Reputation: 3755

you dont need to do a lot/anything special if you are just passing in something quick, for me i was able to just pass in an instance of what i wanted to get injected.

container.Resolve<IFoo>(new List<Parameter>{ new TypedParameter(something.GetType(), something)});

Note: I know what i passed in was not registered with the container.

Upvotes: 1

Shahar Shokrani
Shahar Shokrani

Reputation: 8740

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
    )
);

Upvotes: 1

Cyril Durand
Cyril Durand

Reputation: 16192

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.

Upvotes: 11

Related Questions