I struggle with how to organize the registration of Autofac components in modules, given that some of the modules themselves have dependencies.
I implemented an abstraction of configuration data (i.e. web.config) in an interface:
interface IConfigurationProvider { T GetSection<T>(string sectionName) where T : System.Configuration.ConfigurationSection; }
together with implementations for ASP.NET ( WebConfigurationProvider
) and "desktop" ( ExeConfigurationProvider
) ExeConfigurationProvider
.
Some of my autofac modules then require IConfigurationProvider
as a constructor parameter, but some of them do not:
class DependentModule : Module { public DependentModule(IConfigurationProvider config) { _config = config; } protected override void Load(ContainerBuilder builder) { var configSection = _config.GetSection<CustomConfigSection>("customSection"); builder.RegisterType(configSection.TypeFromConfig); } private readonly IConfigurationProvider _config; } class IndependentModule : Module { protected override void Load(ContainerBuilder builder) { builder.Register(); } }
Since the extension method RegisterType()
does not accept the registration delegate ( Func<IComponentContext, T>
), for example Register()
, I cannot register the front of IConfigurationProvider
and then allow it when I go to register the type specified in the configuration, something like:
// this would be nice... builder.RegisterType(c => c.Resolve<IConfigurationProvider>().GetSection<CustomConfigSection>("sectionName").TypeFromConfig);
This means that I need to be able to register modules with and without dependency on IConfigurationProvider
.
Obviously, how to manually create an instance of each module and register it:
IConfigurationProvider configProvider = ...; var builder = new ContainerBuilder(); builder.RegisterModule(new DependentModule(configProvider)); builder.RegisterModule(new IndependentModule()); using (var container = builder.Build()) { ... }
But I donβt want to manually create instances of my modules - I want to check assemblies for modules and register them automatically (as discussed in this question ). So I have to use reflection to scan the assembly for IModule
types and use Activator.CreateInstance
to create registers. But how do I know whether to pass the IConfigurationProvider
parameter as a constructor parameter. And what happens when other modules have additional or different dependencies?
There should be an easier way to accomplish the main task: register the type specified in some configuration provided through the interface, right? So how do I do this?