Umbraco 9 Registering a Service and Exposing it to Dependency Injection
Hi All,
Does anyone know how to convert this code to Umbraco 9.
I am trying to compose a service I have created called SiteHelper: ISiteHelper so I can then use it in my controllers using DI
public class SiteHelperComposer : IUserComposer
{
public void Compose(Composition composition)
{
composition.Register<ISiteHelper, SiteHelper>(Lifetime.Singleton);
}
}
Here is an example of my service I am trying to compose.
public interface ISiteHelper
{
string TestMethod();
}
public class SiteHelper : ISiteHelper
{
private readonly ILogger _logger;
public SiteHelper(ILogger logger)
{
_logger = logger;
}
public string TestMethod()
{
try
{
throw new Exception();
}
catch (Exception e)
{
_logger.LogError(e, "Index | Exception: {0} | Message: {1} | Stack Trace: {2}", e.InnerException != null ? e.InnerException.ToString() : "", e.Message != null ? e.Message.ToString() : "", e.StackTrace);
}
return "This returned a value";
}
}
I have been playing around with the following code in V9 but haven't got it to work.
Umbraco 9 Registering a Service and Exposing it to Dependency Injection
Hi All,
Does anyone know how to convert this code to Umbraco 9.
I am trying to compose a service I have created called SiteHelper: ISiteHelper so I can then use it in my controllers using DI
Here is an example of my service I am trying to compose.
I have been playing around with the following code in V9 but haven't got it to work.
I kind of had some success with this if I got rid of the logger but couldn't get it to work including the logger or other dependencies.
Kind Regards
David
this should fix it :)
Explained here https://stackoverflow.com/questions/52921966/unable-to-resolve-ilogger-from-microsoft-extensions-logging/57590076#57590076
Did it work out for you? :)
I haven't tried yet. I will have a look this evening when tuning in to code garden.
usually just work on this stuff a couple of hours on a night or on a weekend. I will let you know how I get on.
Hi Mathias,
Thanks for helping me get that working. You was correct the composing was failing because of the ILogger was injected inforrectly.
For completion here is my code.
Thanks again.
David
I actually wrote a more in depth blog article on this subject if anyone is interested.
https://www.umbrajobs.com/blog/posts/2021/june/how-to-compose-a-custom-service-in-umbraco-9/
hope this info helps someone. Feel free to comment here if you need further help.
is working on a reply...
This forum is in read-only mode while we transition to the new forum.
You can continue this topic on the new forum by tapping the "Continue discussion" link below.