Hi everyone, from Umbraco documentation it’s clear that we shouldn’t use n Singleton accessors like: ApplicationContext.Current or UmbracoContext.Current.
But I’m not sure how to re-write this piece of code to the new guidelines any help or pointers much appreciated.
var tempMember = ApplicationContext.Current.Services.MemberService.GetByEmail(email);
it depends a little bit on where that line of code is running from:
if you are ruining it in a Controller. that inherits something like UmbracoAuthorizedController, UmbracoApoController or SurfaceController you can access the services via the Services member/
Services.MemberService.GetByEmail(email).
if its in your own code class, then you should use Dependency Injection to include the MemberService in the class.
public class MyMemberThing
{
private readonly IMemberService _memberService;
public MyMemberThing(IMemberService memberService)
{
_memberService = memberService;
}
public void MyEmailMethod(string email)
{
_memberService.GetByEmail(email);
}
}
if you do this, you need to register your class via a 'composer' . this runs at startup and does the dependency injection magic for you. so what ever needs your membersthing class can use it in the same way and it will get the MemberService sent to its constructor.
public class MyMemberComposer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<MyMemberThing>();
}
}
if you are doing this is razor. (as cshtml) file then you will probibly have to use Current.
Umbraco 8 - ApplicationContext
Hi everyone, from Umbraco documentation it’s clear that we shouldn’t use n Singleton accessors like: ApplicationContext.Current or UmbracoContext.Current.
But I’m not sure how to re-write this piece of code to the new guidelines any help or pointers much appreciated.
Hi Tom,
it depends a little bit on where that line of code is running from:
if you are ruining it in a Controller. that inherits something like UmbracoAuthorizedController, UmbracoApoController or SurfaceController you can access the services via the Services member/
if its in your own code class, then you should use Dependency Injection to include the MemberService in the class.
if you do this, you need to register your class via a 'composer' . this runs at startup and does the dependency injection magic for you. so what ever needs your
membersthing
class can use it in the same way and it will get theMemberService
sent to its constructor.if you are doing this is razor. (as cshtml) file then you will probibly have to use Current.
If you are in razor you are probably better using the Membership Helper. e.g
Thanks Kevin :)
is working on a reply...