我正在将 IoC 添加到现有的 Web 表单项目中,但在注入(inject)用户控件的依赖项(尤其是母版页中的动态用户控件)时遇到了一些麻烦。
在母版页上,我加载一些用户控件:
protected override void OnLoad(EventArgs e)
{
bool processComplete = false;
var page = Page as BasePage;
if (page != null && HttpContext.Current.User.Identity.IsAuthenticated)
processComplete = page.processComplete ;
var segments = this.Request.Url.Segments;
Control bodyheader = null;
if (processComplete )
{
if (segments.Count() > 1 && segments[1].StartsWith("evaluation", true, System.Globalization.CultureInfo.CurrentCulture))
bodyheader = Page.LoadControl("~/Themes/HWP/HeaderNoSearch.ascx");
else
bodyheader = Page.LoadControl("~/Themes/HWP/Header.ascx");
}
else if (segments.Count() > 1 && segments[1].StartsWith("welcome", true, System.Globalization.CultureInfo.CurrentCulture))
{
bodyheader = Page.LoadControl("~/Themes/HWP/plainHeaderAuth.ascx");
}
else
{
bodyheader = Page.LoadControl("~/Themes/HWP/plainHeaderAuth.ascx");
}
plcBodyHeader.Controls.Add(bodyheader);
Control bodyfooter = Page.LoadControl("~/Themes/HWP/Footer.ascx");
plcBodyFooter.Controls.Add(bodyfooter);
base.OnLoad(e);
}
每个用户控件都有一些依赖性。我可以在每个用户控件中手动注入(inject)依赖项:
protected override void OnInit(EventArgs e)
{
var cpa = (IContainerProviderAccessor)HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
cp.RequestLifetime.InjectProperties(this);
base.OnInit(e);
}
但这似乎违背了使用 IoC 的目的。 MasterPage -> Page -> UserControls 应该如何构建以允许 DI?如何在动态用户控件中注入(inject)属性?我应该使用构造函数注入(inject)吗?
我正在使用 Autofac,但我认为这个问题与 IoC 无关。
最佳答案
您走在正确的道路上。我通常创建一个继承自UserControl的BaseUserControl类。然后从这个BaseUserControl类继承所有UserControls。
将所有必需的依赖项放入该 BaseUserControl 类中。
public class BaseUserControl : UserControl
{
public ISomeService SomeService { get; set; }
public IOtherService OtherService { get; set; }
public BaseUserControl()
{
var cpa = (IContainerProviderAccessor)
HttpContext.Current.ApplicationInstance;
var cp = cpa.ContainerProvider;
cp.RequestLifetime.InjectProperties(this);
}
}
您可能会认为这有点浪费,因为并非所有用户控件都使用所有依赖项。
Mark Seemann 在 .NET 中的依赖注入(inject)一书中指出,依赖注入(inject)非常快并且从来都不是问题。如果您认为您的应用程序很慢,那么它可能来自代码的其他位置(而不是来自依赖项注入(inject))。
如果你想使用构造函数注入(inject),请看这个answer .
关于asp.net - Ioc 和 WebForms - 如何在用户控件中注入(inject)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27507377/