But essentially create your custom helper service class like so:
public class JasperHelperService : IJasperHelperService
{
private readonly IMemberService _memberService;
public JasperHelperService(IMediaService memberService)
{
_memberService = memberService;
}
public string SomeHelperMethod(string userName){
var member = _memberService.GetByUsername(userName);
return member.Id;
}
}
You'll need to define an interface for your service
public interface IJasperHelperService
{
public string SomeHelperMethod(string userName);
}
Then register your custom service with an IUserComposer
public class RegisterJasperHelperServiceComposer : IUserComposer
{
public void Compose(Composition composition)
{
//Lifetime.Request if it depends on the current request, eg depends context of current member or current published content item, or use Lifetime.Singleton if it's the same context across every request
composition.Register<IJasperHelperService, JasperHelperService>(Lifetime.Request);
}
}
Now in your controllers you can access your HelperService like so
public class BlogPostController : Umbraco.Web.Mvc.RenderMvcController
{
private readonly IJasperHelperService _jasperHelperService;
public BlogPostController(IJasperHelperService jasperHelperService)
{
_jasperHelperService= jasperHelperService;
}
public override ActionResult Index(ContentModel model)
{
var memberSomething = _jasperHelperService.SomeHelperMethod("jasper");
}
}
You could access the JasperHelperService in a view by
Using MemberService in Helper class (Umbraco v8)
Hi!
I'm successfully using the Services.MemberService (and other Services) in my Controller classes).
Like so:
Now I've come to the point that I need a Helper class for some helper methods. In these methods I need access to the MemberService.
This helper class is preferably a static class.
I've looked at dependency injection, but haven't found a way to access the Services in a custom class.
Is it possible?
Hi Jasper
Yes it's possible to access services in a custom class using DI, but your service wouldn't be static.
Using DI:
(There is some information here that might help: https://our.umbraco.com/documentation/Getting-Started/Code/Umbraco-Services/)
But essentially create your custom helper service class like so:
You'll need to define an interface for your service
Then register your custom service with an IUserComposer
Now in your controllers you can access your HelperService like so
You could access the JasperHelperService in a view by
regards
Marc
Thanks Marc, this was really helpful!
is working on a reply...