Reputation: 1158
I've not been using Autofac for long, and I was wondering which is the best way to register parameters:
using Register() method, with lamba expression
builder.Register(a => new SomeClass(config))
.As<ISomeClass>();
using RegisterType() method and WithParameter()
builder.RegisterType<SomeClass>()
.WithParameter(new NamedParameter("config", config))
.As<ISomeClass>();
The second way looks nicer to me, but I guess it's pretty dangerous to use as the name of the parameter can change.
Upvotes: 0
Views: 309
Reputation: 1124
Use the way which better suits your needs. If you don't need much flexibility then use the first approach. But as soon as SomeClass
dependencies will grow, you might want to use more flexible approaches like NamedParameter
.
One more option is using named component registrations like
builder.RegisterInstance(config).Named<Config>("DefaultConfig");
builder.Register((c, p) => new SomeClass(p.Named<Config>("DefaultConfig")))
.As<ISomeClass>();
Read more about those the topic from Resolve Parameters documentation
In any case the best practice would be to cover all your registrations by unit tests as well to avoid unexpected results.
Upvotes: 1