[英]Property Injection into an Action Filter
I'm trying to get Property Injection working on a Custom Action Filter Attribute. 我正在尝试让“属性注入”在“自定义操作过滤器”属性上运行。 It is working as it is supposed to, however, I'd like to use DI on the Property itself.
它正在按预期的方式运行,但是,我想在属性本身上使用DI。 My filter looks like this
我的筛选器看起来像这样
[AttributeUsage(AttributeTargets.Class)]
public sealed class HeaderFilterAttribute : ActionFilterAttribute
{
public IMarketService MarketService
{ get; set; }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var view = (ViewResultBase)filterContext.Result;
if (view != null)
{
BaseViewModel viewModel = view.ViewData.Model as BaseViewModel;
if (viewModel != null)
viewModel.Header = GetHeaderScript();
}
base.OnActionExecuted(filterContext);
}
private string GetHeaderScript()
{
//Use MarketService here and return header script
return "script";
}
}
This is how I'm configuring the property using StructureMap inside my BootStrapper class. 这就是我在BootStrapper类中使用StructureMap配置属性的方式。
//HeaderFilterAttribute
IMarketRepository marketRepository = new SqlMarketRepository();
IMarketService marketService = new MarketService(marketRepository);
ObjectFactory.Container.Configure(r => r.ForConcreteType<HeaderFilterAttribute>().
Configure.WithProperty("MarketService").
EqualTo(marketService));
My problem is I do not have access to SqlMarketRepository since all my concrete types are injected via DI and I really don't want to use concrete types in my bootstrapper. 我的问题是我无法访问SqlMarketRepository,因为我所有的具体类型都是通过DI注入的,我真的不想在我的引导程序中使用具体类型。 So the ultimate question now is, how do I inject MarketService into the Filter attribute without resorting to the above?
因此,现在的最终问题是,如何不借助上述方法将MarketService注入Filter属性? :)
:)
In your ObjectFactory.Initialize() call, add the following line: 在您的ObjectFactory.Initialize()调用中,添加以下行:
SetAllProperties(x => x.OfType<IMarketService>());
That will inject the configured IMarketService instance into any property of type IMarketService, on any object retrieved from the container. 这会将配置好的IMarketService实例注入到从容器中检索到的任何对象上的IMarketService类型的任何属性中。
I think you need a custom action invoker implementation that will resolve the filters. 我认为您需要一个可解决过滤器的自定义操作调用程序实现。 You can dig a Windsor sample out of my company's implementation (about 1/2 way down).
您可以从我公司的实施中提取一个Windsor示例(下降约1/2倍)。 There should be several more available online.
网上应该还有更多可用的内容。 I know I've seen some on this site.
我知道我在这个网站上看到了一些。
PS. PS。 I noticed you're using a base view model to populate a header.
我注意到您正在使用基本视图模型填充标头。 I'd recommend using the ViewData[] collection with a static key instead of inheritance in your view model.
我建议将ViewData []集合与静态键一起使用,而不要在视图模型中使用继承。 :)
:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.