0

I'm wondering if there's a convention-based approach for the registering the following in 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>>();

The above works fine, but I'm just wondering if there's a cleaner and less repetitive way of doing it. I had a look at this post: Resolving Generic Interface with Autofac, but it's not quite the same scenario.

Thanks!

Community
  • 1
  • 1
dgolds
  • 41
  • 4

1 Answers1

1

You could replace the .As<...>() with .AsImplementedInterfaces(). Beyond that, you could use:

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

or something like that.

Jim Bolla
  • 8,265
  • 36
  • 54