我正在使用Simple Injector IoC框架,我希望能够在运行时更改依赖项注册。例如,我有两个实现,A
和B
,接口为I
。实现A
是在应用程序启动时注册的,但根据某些可在运行时更改的标志,我希望切换实现。我们目前正在执行我们的BaseController
的OnActionExecuting
事件,这是我们所有控制器继承的事件。这是我正在尝试做的示例代码。如何使用简单注入器在运行时更改依赖注册?
protected override void OnActionExecuting(
ActionExecutingContext filterContext)
{
if (IsRuntimeFlag)
{
// check current implementation type and
// change implementation to A
}
else
{
// check current implementation type and
// change implementation to B
}
base.OnActionExecuting(filterContext);
}
在此先感谢您的帮助。
我建议结合工厂和战略模式,而不是使用DI容器为此。尽早使用Container来解析对象图。参见[Composition Root](http://blog.ploeh.dk/2011/07/28/CompositionRoot.aspx)。 – TrueWill
您是否需要手动执行此操作?使用IOC容器框架怎么样? –