I think you have a couple of options, knowing that, in general, Autofac needs to have the type inside the container in order to resolve it.
The easiest and most straightforward solution is to just register the type. If you have a reference to the Type
at the time you're building your container, you can use that to register it with Autofac and resolve it.
Type customType = GetTheRuntimeType();
var builder = new ContainerBuilder();
builder.RegisterType(customType);
You can add more to that if you want (InstancePerLifetimeScope()
, or As<IInterface>()
, or whatever) but that'd work.
If you don't have the type at the time you're building the container then you could choose to manually inject properties after the fact. It's kind of like service location but it'd mean you could keep the type creation separate.
Type customType = GetTheRuntimeType();
var builder = new ContainerBuilder();
// register everything else, then
var container = builder.Build();
using(var scope = container.BeginLifetimeScope())
{
var instance = Activator.CreateInstance(customType);
scope.InjectUnsetProperties(instance);
}
It wouldn't be constructor injection, instead it'd be properties. But it's pretty easy.
The third option is the most integrated but possibly the hardest. You could implement a registration source that tells Autofac about your type. I'm not going to put the code here because there's a lot to it and I'm not at a compiler, but read the docs and check it out. There are examples in the docs. This is how Autofac dynamically handles things like IEnumerable<T>
when you never explicitly registered that. You could come up with any set of runtime types you want and all of them could be dynamically inserted into the container using a registration source.
If you have the ability to do the first option and just register the type, I'd recommend that. It's the easiest way to do a good integration.
The property injection thing works but it's kind of a hack. Depends on how long lived your solution needs to be or if you just need to get it to work really quick.
The registration source solution is definitely the most robust. If you don't have the runtime type before you create the container then this is the best option. It's harder to get working at the outset but it'll be more extensible because you could piggyback any additional runtime type needs off of it.
Whatever you do, don't use Update()
to add the registration after your container is built. It's been marked obsolete for a year or so now and is going to be coming out. It won't serve you as a long term solution.