I’m using Autofac. I want to inject a different implementation of a dependency based on an attribute I apply to the constructor parameter. For example:
class CustomerRepository
{
public CustomerRepository([CustomerDB] IObjectContainer db) { ... }
}
class FooRepository
{
public FooRepository([FooDB] IObjectContainer db) { ... }
}
builder.Register(c => /* return different instance based on attribute on the parameter */)
.As<IObjectContainer>();
The attributes will be providing data, such as a connection string, which I can use to instance the correct object.
How can I do this?
It sounds like you want to provide different implementations of
IObjectContainertoCustomerRepositoryandFooRepository. If that is the case, attributes might be a thin metal ruler. Instead, I’ll show you how I would implement multiple implementations with Autofac.(Calls such as
.ContainerScoped()have been left out for brevity.)First, register a version of
IObjectContainerfor each connection string by naming the registrations:Then, resolve the specific instances in the repository registrations:
This leaves the repositories free of configuration information: