Since the choice is based on the type of controller, you can make the descision in a custom IControllerFactory
. For instance:
public class ConnectionSelector {
public bool AsReadOnly { get; set; }
}
private class ReadOnlySwitchControllerFactory : DefaultControllerFactory {
private readonly Container container;
public ReadOnlySwitchControllerFactory(Container container) {
this.container = container;
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType) {
var selector = this.container.GetInstance<ConnectionSelector>();
selector.AsReadOnly =
typeof(IReadOnlyController).IsAssignableFrom(controllerType);
return base.GetControllerInstance(requestContext, controllerType);
}
}
You can register this as follows:
container.RegisterPerWebRequest<ConnectionSelector>();
container.RegisterPerWebRequest<DbContext>(() => new DbContext(
container.GetInstance<ConnectionSelector>().AsReadOnly
? "ReadOnlyConnection"
: "NormalConnection"));
container.RegisterSingle<IControllerFactory>(
new ReadOnlySwitchControllerFactory(container));