简体   繁体   English

我可以使用IoC容器来创建ASP.NET webforms页面和控件吗?

[英]Can I use an IoC container to create ASP.NET webforms pages and controls?

With ASP.NET MVC it is pretty easy to integrate an IoC container to create the controllers. 使用ASP.NET MVC,可以很容易地集成IoC容器来创建控制器。

Is the same thing also possible with webforms to create the pages and controls and pass them any dependencies? webforms是否也可以创建页面和控件并将它们传递给任何依赖项? If yes, where do I have to plug it in? 如果是的话,我该把它插在哪里?

是的,你可以,这里是Spring.NET如何做到这一点的一个例子。

Castle Windsor was the first major IoC container for ASP.NET. Castle Windsor是ASP.NET的第一个主要IoC容器。 See this question discussing how it can be used with Web forms. 请参阅问题,讨论如何将其与Web表单一起使用。

Not directly, as Web Forms does not allow any code to take control of Page and Control instantiation. 不直接,因为Web窗体不允许任何代码控制页面和控件实例化。 So something like a Page Factory is not feasible, and you can't do constructor injection. 所以像页面工厂这样的东西是不可行的,你不能做构造函数注入。

But there are work arounds/hacks that can buy you setter injection as others have mentioned. 但正如其他人所提到的那样,周围/黑客可以为你买入注射器。

另一个好方法是使用Model-View-Presenter模式,并将您的依赖项注入到演示者的构造函数中。

I know this question is very old but in the .NET Framework 4.7.2+ you can have constructor injection in ASP.NET WebForm pages and user controls. 我知道这个问题很老,但在.NET Framework 4.7.2+中,您可以在ASP.NET WebForm页面和用户控件中进行构造函数注入。

From this official blog post : 来自这篇官方博文

Areas that Dependency Injection can be used 可以使用依赖注入的区域

There are many areas you can use Dependency Injection in WebForms applications now. 现在,您可以在WebForms应用程序中使用依赖注入的许多方面。 Here is a complete list. 这是一个完整的清单。

  • Pages and controls WebForms page User control Custom control 页面和控件WebForms页面用户控件自定义控件
  • IHttpHandler and IHttpHandlerFactory IHttpHandlerIHttpHandlerFactory
  • IHttpModule Providers IHttpModule提供商
  • BuildProvider BuildProvider
  • ResourceProviderFactory
  • Health monitoring provider 健康监测提供者
  • Any ProviderBase based provider created by System.Web.Configuration.ProvidersHelper.InstantiateProvider . System.Web.Configuration.ProvidersHelper.InstantiateProvider创建的任何基于ProviderBase的提供程序。 eg custom session state provider 例如自定义会话状态提供者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM