Simple Injector: Different DbContext for selected controllers

自古美人都是妖i 提交于 2019-12-06 12:45:31

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));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!