【问题标题】:Auto Wiring Repository With Generic Type Parameters in AutofacAutofac中具有通用类型参数的自动接线存储库
【发布时间】:2014-04-09 00:47:35
【问题描述】:

我想知道是否有基于约定的方法在 Autofac 中注册以下内容:

builder.RegisterType<BatchDocumentRepository>()
    .As<IRepository<BatchDocument, IEnumerable<BatchDocument>, int>>();
builder.RegisterType<BatchRepository>()
    .As<IRepository<Batch, IEnumerable<Batch>, int>>();
builder.RegisterType<DeploymentReleaseRepository>()
    .As<IRepository<DeploymentRelease, IEnumerable<DeploymentRelease>, int>>();
builder.RegisterType<DeploymentRepository>()
    .As<IRepository<Deployment, IEnumerable<Deployment>, int>>();

上面的工作正常,但我只是想知道是否有一种更清洁、更少重复的方法。我看过这个帖子:Resolving Generic Interface with Autofac,但情况并不完全相同。

谢谢!

【问题讨论】:

    标签: c# generics autofac


    【解决方案1】:

    您可以将.As&lt;...&gt;() 替换为.AsImplementedInterfaces()。除此之外,您还可以使用:

    builder.RegisterAssemblyTypes()
        .Where(t => t.GetInterfaces()
                     .Any(i => i.IsGenericType &&
                               i.GetGenericDefinition() == typeof(IRepository<>)))
        .AsImplementedInterfaces();
    

    或类似的东西。

    【讨论】:

      猜你喜欢
      • 2021-07-23
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      相关资源
      最近更新 更多