I am trying to resolve dependencies based on a condition.
private static readonly Dictionary<string, Action<ContainerBuilder>> QRTypeDictionary =
new Dictionary<string, System.Action<ContainerBuilder>> () {
{ "REST" , (builder)=> builder
.RegisterType<RestPublisher>()
.As<Publisher>()},
{ "DB" , (builder)=> builder
.RegisterType<DBPublisher>()
.As<Publisher>()}
}
I am just looking to make sure if this is the only way to resolve dependencies based on conditions. I have been using Ninject so far and am looking for something like the following:
kernel.Bind<Publisher>()
.To<DbPublisher>()
.When(x => Defs.AppSettings.PublisherType == "DB")
Just want to make sure I am doing the right thing with Autofac
I can see 3 solutions to achieve what you want.
Using a lambda
builder.RegisterType<DbPublisher>().AsSelf();
builder.RegisterType<RestPublisher>().AsSelf();
builder.Register(c => {
switch(Defs.AppSettings.PublisherType){
case "DB":
c.Resolve<DbPublisher>();
break;
case "REST":
c.Resolve<RestPublisher>();
break;
default:
throw new NotSupportedException();
}
}).As<IPublisher>();
Using named registration
builder.RegisterType<DbPublisher>().Named<IPublisher>("DB");
builder.RegisterType<RestPublisher>().Named<IPublisher>("REST");
builder.Register(c => {
var index = c.Resolve<IIndex<String, IPublisher>>();
return index[Defs.AppSettings.PublisherType]
}.As<IPublisher>();
Conditional registration
if Defs.AppSettings.PublisherType
is defined during registration process, you can simply conditionally register your dependency :
switch(Defs.AppSettings.PublisherType){
case "DB":
builder.RegisterType<DbPublisher>().As<IPublisher>();
break;
case "REST":
builder.RegisterType<RestPublisher>().As<IPublisher>();
break;
default:
throw new NotSupportedException();
}
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