[I previously answered and indicated you couldn't register new tenants on the fly. That was incorrect and I'm updating accordingly.
I think you can do what you want with Autofac.Extras.Multitenant, though you'll want to test it thoroughly (and let us know if it's broken).
- Tenants don't have differing dependencies, only the data stored within the instances: Register common dependencies at the container level, but for instances that have different data per tenant, register those as
InstancePerTenant
.
- I have some instances that need to be per tenant, to ensure no leakage of data: Use the
InstancePerTenant
registration extension.
- I determine a tenant based off the URL they access the web site with: Implement your own
ITenantIdentificationStrategy
that looks at the URL and converts to a tenant ID.
The new tenants need to be registered during execution item was something I previously was thinking wouldn't work but now I think it will.
When you create a tenant at app startup, it's like this:
// Configure application-level defaults.
var builder = new ContainerBuilder();
builder.RegisterType<Consumer>().As<IDependencyConsumer>().InstancePerDependency();
builder.RegisterType<BaseDependency>().As<IDependency>().SingleInstance();
var appContainer = builder.Build();
// Configure tenant identification and start the multitenant container.
var tenantIdentifier = new MyTenantIdentificationStrategy();
var mtc = new MultitenantContainer(tenantIdentifier, appContainer);
// Configure overrides for existing tenants.
mtc.ConfigureTenant('1', b => b.RegisterType<Tenant1Dependency>().As<IDependency>().InstancePerDependency());
mtc.ConfigureTenant('2', b => b.RegisterType<Tenant2Dependency>().As<IDependency>().SingleInstance());
// Set the MVC dependency resolver.
DependencyResolver.SetResolver(new AutofacDependencyResolver(mtc));
If you need to create a tenant during app runtime, you should be able to do that as long as you haven't previously configured the tenant (no duplicate tenant IDs).
I think it'd work something like this:
// Get the current application container.
var mtc = AutofacDependencyResolver.Current.ApplicationContainer as MultitenantContainer;
// Configure the new tenant.
mtc.ConfigureTenant('3', b => b.RegisterType<Tenant3Dependency>().As<IDependency>().InstancePerDependency());
Actually, I think it's as simple as that. Again, as long as you don't try to reconfigure an existing tenant you should be OK.