使用 autofac 将属性注入 asp.net 页面:重写 PropertyInjectionModule 行为以注入值/设置
是否可以通过 autofac 的 PropertyInjectionModule 将值/设置注入 ASP.NET 页面?我的印象是默认处理程序行为是搜索属性并查找与容器中的服务匹配的任何类型。
例如对于一个页面:
public class MyPage: System.Web.UI.Page {
public IDataProvider DataProvider { get; set; }
public bool SomeSetting {get; set; }
public bool AnotherSetting { get; set; }
public string MySettings { get; set; }
// stuff
}
我想也许你可以指定属性:
builder.RegisterType<MyPage>()
.WithProperty("SomeSetting", true)
.WithProperty("AnotherSetting", false)
.WithProperty("MySettings", "do-re-mi");
但它似乎不起作用。
我意识到我可以设置 IMyPageConfig 界面并以这种方式提供设置,但这些是可能需要或可能不需要设置的可选属性。
Is it possible to inject values/settings into ASP.NET Pages via autofac's PropertyInjectionModule? I get the impression that default handler behavior is to search for properties and find any types that match services in the container.
eg for a page:
public class MyPage: System.Web.UI.Page {
public IDataProvider DataProvider { get; set; }
public bool SomeSetting {get; set; }
public bool AnotherSetting { get; set; }
public string MySettings { get; set; }
// stuff
}
I thought maybe you could specify properties:
builder.RegisterType<MyPage>()
.WithProperty("SomeSetting", true)
.WithProperty("AnotherSetting", false)
.WithProperty("MySettings", "do-re-mi");
but it doesn't seem to work.
I realise I could setup an IMyPageConfig interface and provide settings that way but these are optional properties that may or may not need to be set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
ASP.NET
Page
中的 IoC 有一点限制 - 尽管模块将属性注入到页面中,但它无法真正使用 Autofac 的常规依赖项注入功能。在 WebForms 中,人们通常解决这个问题的方法是使用诸如“模型-视图-演示器”之类的东西,其中页面只是一个“哑”视图,演示器是逻辑(和正确的依赖注入)发生的地方。
查看 http://webformsmvp.com/ - 我认为那里有一个 IoC 示例和 Autofac 支持。
IoC in ASP.NET
Page
s is a bit limited - although the module is injecting properties into the page, it can't really use Autofac's regular dependency injection features.In WebForms the way people typically get around this is to use something like Model-View-Presenter, where the page is just a 'dumb' view and the presenter is where the logic (and proper dependency injection) takes place.
Check out http://webformsmvp.com/ - I think there is an IoC example and Autofac support available there.