Autofac is one of the most popular IoC containers for application development. Like other IoC containers – Unity, Ninject, etc… – it provides a way to reduce efforts for registration of components. In terms of Autofac, it is called Module. With modules, we can bunch up several components for grouping purpose, let’s say DbModule, ServiceModule, RepositoryModle and so forth.
This concept is particularly useful when you are considering flexible application development by allowing 3rd party extensions. However, the problem is that we have to explicitly declare which module should be registered like:
public class MyModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<MyComponent>().As<IMyComponent>();
}
}
`</pre>
Then this module can be registered in this way:
<pre>`builder.RegisterModule(new MyModule());
`</pre>
If you have several modules that are always registered, manual addition like above should be fine. However, if you have tens of modules to be added and more modules will be added on requests, this manual addition will not be desirable. For this case, we can achieve this with `Web.config` or `App.config` but XML document is basically not good for human readability. Therefore, we might have to load such modules in dynamic/automatic way.
This is an example how to make it.
<pre>`private void RegisterModules(ContainerBuilder builder)
{
// #1
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
if (String.IsNullOrWhiteSpace(path))
{
return;
}
// #2
var assemblies = Directory.GetFiles(path, "Module*.dll", SearchOption.TopDirectoryOnly)
.Select(Assembly.LoadFrom);
foreach (var assembly in assemblies)
{
// #3
var modules = assembly.GetTypes()
.Where(p => typeof (IModule).IsAssignableFrom(p)
&& !p.IsAbstract)
.Select(p => (IModule) Activator.CreateInstance(p));
// #4
foreach (var module in modules)
{
builder.RegisterModule(module);
}
}
}
#1
: Firstly, we need to get a directory path running the application.#2
: Then, find all assemblies related to modules. In the code, all assembly files for modules have names starting withModule
.#3
: All modules are extracted from each assembly file. Make sure that each module MUST have a parameterless constructor to get resolved by Autofac.#4
: All modules are finally registered.
This is it. From now on, you can register as many modules as you want, regardless of the number of assemblies. The code above is just a working example with a quick and dirty way. Therefore, you should tidy up the code or even make the number of code lines smaller.
The sample code can be found at: https://github.com/devkimchi/Autofac-Dynamic-Moduling