dependency-injectionorchardcmsautofacproperty-injection

Property Injection and/or Adding a Controller to an Alternate MenuItem View


I'm trying (and failing) to get property injection working in Orchard CMS.

This is necessary, because the below code is acting something like a code-behind for a view (horrible I know). The reason being that the view doesn't have a controller that I can use constructor injection on, because this is an alternate view for a MenuItem, i.e. MenuItemLink-MyCustomMenuItem.cshtml.

Not much more to say than that, except what's in the comments (note the NULL comment for the property that I am trying to set in the code below).

Oh, I've also tried adapting the property injection code from Orchard's LoggingModule, but equally that doesn't work for me either.

How do I :

a. get the below property injection to work? (I'm pretty sure I will need it at some point regardless)

b. (if possible) get my own controller/driver in the way of the view so I can use constructor injection on the controller instead?

using System.Diagnostics;
using System.Xml.Linq;
using Autofac;
using Autofac.Core;
using Orchard;
using Module = Autofac.Module;

namespace MyCo.MyCustomMenuItem.Services 
{

    public class MyCustomMenuItemModule : Module 
    {

        protected override void AttachToComponentRegistration(
            IComponentRegistry componentRegistry, 
            IComponentRegistration registration)
        {
            if (implementationType.ToString() == 
                        "MyCo.MyCustomMenuItem.Services.MyCustomMenuItem") 
            {
                // this does get called, but doesn't have the desired effect
                registration.Activated += (s, e) => 
                         e.Context.InjectUnsetProperties(e);
            }
        }

    }

    public interface IFeedX : IDependency 
    {
        XDocument GetResource();
    }

    public class FeedX : IFeedX
    {
        public XDocument GetResource() 
        {
            return new XDocument();
        }
    }

    public interface IMyCustomMenuItem : IDependency 
    {
        XDocument GetResourceData();

        IFeedX FeedX { get; set; }
    }   

    public class MyCustomMenuItem : IMyCustomMenuItem
    {
        public IFeedX FeedX { get; set; }

        // called direct by razor view
        public XDocument GetResourceData()
        {
            Debug.WriteLine(FeedX); // NULL??

            return FeedX.GetResource(); 
        }

    }

}

Solution

  • You definitely should not do anything of the sort in the view. I think this article describes a scenario that is close to what you're trying to achieve: http://www.davidhayden.me/blog/dynamically-injecting-menu-items-in-orchard-cms