Property Injection into an Action Filter

﹥>﹥吖頭↗ 提交于 2019-12-22 06:27:34

问题


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";
   }
}

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));

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? :)


回答1:


In your ObjectFactory.Initialize() call, add the following line:

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.




回答2:


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). There should be several more available online. I know I've seen some on this site.

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. :)



来源:https://stackoverflow.com/questions/3876436/property-injection-into-an-action-filter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!