解决条件依赖关系autofac

时间:2016-04-24 08:26:25

标签: c# autofac

我正在尝试根据条件解决依赖关系。

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>()}
 }

我只是想确定这是否是根据条件解决依赖关系的唯一方法。到目前为止,我一直在使用Ninject,我正在寻找以下内容:

kernel.Bind<Publisher>()
      .To<DbPublisher>()
      .When(x => Defs.AppSettings.PublisherType == "DB")

只是想确保我使用Autofac做正确的事情

1 个答案:

答案 0 :(得分:8)

我可以看到3种解决方案来实现您的目标。

  1. 使用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. 使用命名注册

    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. 条件注册

    如果在注册过程中定义Defs.AppSettings.PublisherType,您只需有条件地注册您的依赖项:

    switch(Defs.AppSettings.PublisherType){
        case "DB":
            builder.RegisterType<DbPublisher>().As<IPublisher>();
            break; 
        case "REST":
            builder.RegisterType<RestPublisher>().As<IPublisher>(); 
            break; 
        default:
            throw new NotSupportedException(); 
    }