Search code examples
c#autofac

How do I register multiple concrete types using assembly scanning in Autofac?


I have an assembly with multiple classes that I'd like to register using assembly scanning in Autofac. Some requirements:

  • There is more than one base type that I use to find the concrete types to register.
  • It should not register abstract classes.
  • Scanning should not be wasteful/redundant, if possible.

Based on the documentation, it seems like the straightforward way of doing this shown below. Note that the Module implementation is inconsequential here; I'm just showing it for completeness).

ContainerBuilder builder;
// ...
builder.RegisterAssemblyTypes(_assembly).AssignableTo<ExpandableDialog>();
builder.RegisterAssemblyTypes(_assembly).AssignableTo<Form>();

Does this cause assembly scanning with each line? Or can I make this more performant by combining them like so?

ContainerBuilder builder;
// ...
builder.RegisterAssemblyTypes(_assembly)
    .AssignableTo<ExpandableDialog>()
    .AssignableTo<Form>();

I feel like the bottom one isn't correct because AssignableTo uses logical AND, so it would require classes to implement both classes above which is wrong. It should be an OR condition.

What is the correct solution here given my list of requirements above?


Solution

  • Usually registration is one time operation and I think in most cases you should not be conserned that much about one time operations performance. Also based on the docs description the second one should register only types which are assignable both to Form and ExpandableDialog.

    If you are concerned about multiple scans you can use Where with predicate:

    builder.RegisterAssemblyTypes(_assembly)
        .Where(t => t.IsAssignableTo<ExpandableDialog>() || t.IsAssignableTo<Form>())
        .AsSelf();