Short version:
Simply put i would like to inject IOptions<TModuleOptions>
(or just TModuleOptions
) into an autofac module, but I cannot figure out how to do so without manually wiring up the options class (which sort of defeats the point).
Is this even possible, and how?
The longer version: I have an ASP.NET Core 3.1 project using Autofac as the DI container, and a module that requires some configuration options. Like a name and a URL for instance.
In the startup i have something like:
public void ConfigureServices(IServiceCollection services)
{
services.Configure<ModuleOptions>(Configuration.GetSection(ModuleOptions.ModuleSettings));
// Stuff remove for brevity
}
public void ConfigureContainer(ContainerBuilder builder)
{
ModuleOptions options = options; // It would be nice with a way to get this here or have it resolved "automagically".
builder.RegisterModule(new CustomModule());
}
I tried different things, but I can't really see how i might go about doing it in a "nice" manner.
The closet I have gotten is by doing the configuration binding manually like so:
var options = this.Configuration.GetSection("Something").Get<ModuleOptions>();
It works, but "feels" like its not the "idiomatic" .net core way of handling things.
Is it possible to achieve what I want using the DI container similar to how I would do it if I was using the MS DI or RegisterType(context => context.Resolve<IOptions<TModuleOptions>>())
?
You can't supply IOptions<T>
to a module like that because it's a circular dependency. A module executes registrations... but in order to resolve the IOptions<T>
you need to build the container, which means you can't register things anymore.
If you think about it, that's actually correct behavior, because technically the IOptions<T>
could end up causing something different to be registered, which would affect the IOptions<T>
, which would change what gets registered, which would affect the IOptions<T>
... yeah.
For bootstrap/app startup code, unfortunately you really can't over-DI it. Your mechanism of getting options from configuration is probably as good as it gets.
The reason you can kind of DI things into Startup
is because internally the .NET Core hosting mechanism builds two containers. The first is super barebones and has config, logging, and hosting things in it; the second is the one you build as part of Startup
and is your app container.
Anyway... yeah, the best you'll get is the config reading, and I'd recommend sticking with that.