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做正确的事情

解决方法:

我可以看到3个解决方案来实现你想要的.

>使用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>(); 

>使用命名注册

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

>有条件的注册

如果在注册过程中定义了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(); 
}
上一篇:ASP.NET Core2使用Autofac实现IOC依赖注入竟然能如此的优雅简便(转载)


下一篇:c# – Autofac:解析同名的IEnumerable注册