Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resolving conditional dependencies autofac

Tags:

c#

autofac

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

like image 871
Farax Avatar asked Apr 24 '16 08:04

Farax


1 Answers

I can see 3 solutions to achieve what you want.

  1. 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>(); 
    
  2. 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>(); 
    
  3. 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(); 
    }
    
like image 161
Cyril Durand Avatar answered Nov 04 '22 17:11

Cyril Durand