房产注入到行为过滤器 [英] Property Injection into an Action Filter
问题描述
我试图让物业注射液对自定义操作筛选器属性的工作。这是因为它的工作是应该,但是,我想使用DI该物业本身。我的过滤器看起来像这样
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. 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";
}
}
这是我如何配置使用StructureMap属性。里面我的引导程序类
This is how I'm configuring the property using StructureMap inside my BootStrapper class.
//HeaderFilterAttribute
IMarketRepository marketRepository = new SqlMarketRepository();
IMarketService marketService = new MarketService(marketRepository);
ObjectFactory.Container.Configure(r => r.ForConcreteType<HeaderFilterAttribute>().
Configure.WithProperty("MarketService").
EqualTo(marketService));
我的问题是我没有SqlMarketRepository访问,因为我所有的具体类型都通过DI和我注入真的不希望在我的引导程序使用的具体类型。因此,最终的现在的问题是,我怎么注入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. So the ultimate question now is, how do I inject MarketService into the Filter attribute without resorting to the above? :)
推荐答案
在你的ObjectFactory.Initialize()调用,添加以下行:
In your ObjectFactory.Initialize() call, add the following line:
SetAllProperties(x => x.OfType<IMarketService>());
这将注入的配置IMarketService实例入式IMarketService的任何财产,从容器中取出任何对象
That will inject the configured IMarketService instance into any property of type IMarketService, on any object retrieved from the container.
这篇关于房产注入到行为过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!