Autofac is a popular dependency injection library that I like to use because they’ve done a lot of legwork to get things to work nicely in .NET Core – (some DI frameworks were not happy with Microsoft’s decision to make a public abstraction for their own DI library).
Modules
If you have a big solution with several different projects, it can be easier to manage each project’s registrations and encapsulate them with an Autofac Module. Then you can register all of the modules together in the application entry point, making registration management a little bit easier.
You can make a module by inheriting Autofac.Module, which is an abstract class that provides some overridable virtual functions to facilitate registration. One of these is ThisAssembly, which is just a shortcut to the assembly containing the module. This is pretty useful as you can use ThisAssembly to scan through and automatically register types based on any criteria you can think of (such as naming conventions or attributes).
Module Base Class
Suppose that you have common registration techniques that you want to just have automatically registered. You could create a base class that does the common registration for you, meaning that all you need to do is any project-specific registration.
Now it is even easier to deal with registrations!
… but there’s a problem:
You can’t use ThisAssembly unless you’re inheriting directly from Module. This makes sense when you think about it – you don’t want ThisAssembly to resolve to the assembly containing the ModuleBase class… it would sort-of defeat the purpose, and cause all kinds of issues during runtime.
Fixing the Base Class
Luckily, since Autofac.Module is abstract with its important bits marked as virtual, its relatively easy to fix. All we need to do is override ThisAssembly to match the assembly of the final inherited type.
Doing this lets us get the type and thus the assembly of the top-level module, allowing ThisAssembly to point to what it normally would if we were inheriting Autofac.Module directly.
Autofac–Automatically registering generics via constructors – Darchuk.NET
[…] in this blog post I talked about using Autofac Modules to reduce your headaches and register things automatically. Since we are using constructor […]