简单注入器:针对所选控制器的不同DbContext [英] Simple Injector: Different DbContext for selected controllers
问题描述
我正在尝试在MVC应用程序中分开读取/写入.我将Ioc用作简单注入器,并且具有以下结构:
I am trying to separate reads/writes in my MVC application. I am using Simple Injector as Ioc and I have following structure:
new Service(
new Repository(
new UnitOfWork(
new DbContext())))
因此,每个网络注册的UnitOfWork
请求其余的Transient
.
So UnitOfWork
registered per web request all the rest Transient
.
因此,想法是创建单独的只读控制器,并注册DbContext
,以在控制器为只读时提供不同的连接.而这可以通过 RegisterWithContext扩展但在我的情况下它将无法正常工作,因为并非所有图形节点都为Transient
.
So idea was to create separate read-only controllers and make a registration of DbContext
to supply a different connection if controller is read-only. And that could be achievable with improved RegisterWithContext extension BUT it will not work in my case because not all graph nodes are Transient
.
有什么办法(比使用改进的RegisterWithContext扩展注册每个存储库更优雅,该地方需要提供另一个只读UnitOfWork
并手动解析传递给Repository
的所有其他参数)所描述的方案可以实现吗?
Is there any way (more elegant than register each Repository with improved RegisterWithContext extension where need to supply another read-only UnitOfWork
and manually resolve all other arguments that passed into Repository
) how the described scenario can be achieved?
推荐答案
由于选择基于控制器的类型,因此可以在自定义IControllerFactory
中进行确定.例如:
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));
这篇关于简单注入器:针对所选控制器的不同DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!