Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Nathan Reece 35 posts 237 karma points
    15 days ago
    Nathan Reece
    0

    Umbraco 8 Dependency injection Custom Helper

    I have been using standard Umbraco helpers and services in my controllers using dependency injection, and that has been working great no problems there

    Someone told me i can use my own classes and push them into my controllers using dependency injection. I had a quick look around and couldn't figure out how to do this

    Has anybody got any tips or can you point me in the right direction?

  • David Armitage 347 posts 1373 karma points
    15 days ago
    David Armitage
    100

    Hi Nathan,

    Its possible yes. Actually very easy.

    -Create a helper class like this. You can pretty much copy this and rename where appropriate.

     using Umbraco.Core;
     using Umbraco.Core.Composing;
    
     namespace Website.Core.Helpers
    {
        public class MyTestHelperComposer : IUserComposer
        {
            public void Compose(Composition composition)
            {
                composition.Register<IMyTestHelper, MyTestHelper>(Lifetime.Singleton);
            }
        }
    
        public interface IMyTestHelper
        {
            string MyTestMethod();
        }
    
    
        public class MyTestHelper : IMyTestHelper
        {
    
            public MyTestHelper()
            {
    
            }
    
            public string MyTestMethod()
            {
                return "some value to be returned";
            }
        }
    }
    

    -Then you can inject your custom helper in the exact same way you do the Umbraco helpers and services.

    Eg.

    public class BlogDetailsPageController : RenderMvcController
        {
            private readonly IMyTestHelper _myTestHelper;
            public BlogDetailsPageController(IMyTestHelper myTestHelper)
            {
                _myTestHelper = myTestHelper;
            }
    
            [HttpGet]
            public override ActionResult Index(ContentModel model)
            {
                var vm = new BlogDetailsPageViewModel(_siteHelper, _membershipSubscriberHelper, model.Content) { };
    
                string test = _myTestHelper.MyTestMethod();
    
                return View("/Views/blogDetailsPage.cshtml", vm);
            }
        }
    

    Hope this helps.

    Regards

    David

  • Nathan Reece 35 posts 237 karma points
    15 days ago
    Nathan Reece
    0

    Thanks for your fast reply Dave, I will try that out now seems easy enough.

  • David Armitage 347 posts 1373 karma points
    15 days ago
    David Armitage
    0

    Yeah its very easy and super useful.

    Umbraco 8 has been a big improvement on stuff like this. Really enforcing people to write good code.

Please Sign in or register to post replies

Write your reply to:

Draft