【发布时间】:2017-08-24 19:57:46
【问题描述】:
根据关于 WebForms 集成的 Simple Injector 文档,它通过代码示例说,我们应该通过使用 [Import] 属性将属性注入到我们的页面中。我们通过根据他们的代码示例连接 Global.asax 文件来启用此行为。它确实适用于 Pages。但是,UserControls 或 MasterPages 的文档中没有任何内容。
在搜索 StackOverflow 以获得可靠的答案时,普遍存在的响应有点过时,并且引用了创建 HttpModule,提供了指向在其 git 存储库 (SimpleInjector.Integration.Web.Forms) 中找到的示例项目的链接。不过,该示例项目已失效,并且从 Simple Injector v4.0 的 repo 中剔除。而且它根本不使用 [Import] 属性的东西。绝对令人困惑。
因此,在不清楚如何前进的情况下,我尝试将两者合并以使其正常工作。
我正在使用最新文档中详述的 Global.asax 引导程序方法,而不是注册新的 HttpModule。我采用了旧 WebForms 集成项目中定义的 container extension methods,并在我的 Bootstrap 中调用它们而不是旧方法。
private static void Bootstrap()
{
var container = new Container();
//container.Options.PropertySelectionBehavior = new ImportAttributePropertySelectionBehavior(); //approach from latest documentation
container.Options.PropertySelectionBehavior = new SimpleInjector.Integration.Web.Forms.WebFormsPropertySelectionBehavior(container.Options.PropertySelectionBehavior); //changed to using WebForms integration way
...
//RegisterWebPages(ref container); //approach from latest documentation
container.RegisterPages(); //changed to using WebForms integration extension methods
}
当我第一次运行它时,container.Verify() 抱怨每个 Page 都实现了 IDisposable 并且它们被注册为 Transient(这让我感到困惑,因为最初的引导似乎也将 Pages 注册为 Transient,但 Verify 确实做到了不要抛出任何错误)。
因此,为了解决这个问题,我将 RegisterPages 扩展方法修改为默认为 Lifestyle.Scoped,从而消除了验证错误。
private static void RegisterBatchAsConcrete(this Container container, IEnumerable<Type> types)
{
foreach (Type concreteType in types)
{
//container.Register(concreteType); //originally registering Transient
container.Register(concreteType, concreteType, Lifestyle.Scoped);
}
}
而且它现在似乎可以工作了,至少对于 Pages 来说是这样。在继续为 UserControls 和 MasterPages 工作之前,我想知道以下问题的答案:
问题
这是正确的方法吗?我是否会因为将 Page、MasterPage 和 UserControl 注册从 Transient 更改为 Scoped 生活方式而遇到问题(性能或其他问题)?还有其他我没有想到的问题吗?
为什么使用 RegisterPages 扩展方法调用与新的 RegisterWebPages 方法相比,Verify 对 Tranisent Lifestyle 有问题?
我应该实际使用 Import 属性,还是不使用?新方法使用 ImportAttributePropertySelectionBehavior,而旧方法使用 WebFormsPropertySelectionBehavior
【问题讨论】:
标签: asp.net dependency-injection webforms inversion-of-control simple-injector