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?
-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);
}
}
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?
Hi Nathan,
Its possible yes. Actually very easy.
-Create a helper class like this. You can pretty much copy this and rename where appropriate.
-Then you can inject your custom helper in the exact same way you do the Umbraco helpers and services.
Eg.
Hope this helps.
Regards
David
Thanks for your fast reply Dave, I will try that out now seems easy enough.
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.
is working on a reply...