When is it appropriate to inject the UmbracoContext and when would it be appropriate to inject the UmbracoContextFactory?
I am looking for documentation on the intended use case for each of these classes. For example, when writing a service that gets content data for a surface controller, what would be the correct class to inject?
Essentially in some places in Umbraco where you might want to inject a custom service of your own creation, the UmbracoContext is not guaranteed to exist, and you would get a boot error - eg a Component or ContentFinder - here therefore if you need to access the Umbraco published Cache you would inject the UmbracoContextFactory and wrap a call to EnsureUmbracoContext in a using statement, to get reference to the content cache - there is an example in the link above.
If you are inheriting from one of Umbraco's special base classes, eg RenderMvcController, SurfaceController, UmbracoApiController
then you already have access to the UmbracoContext, via the 'UmbracoContext' property that they all expose.
eg
using System.Web.Mvc;
using Umbraco.Web.Mvc;
namespace Umbraco8.Controllers
{
public class TestSurfaceController : SurfaceController
{
// GET: TestSurface
public ActionResult Index()
{
var somePublishedContent = UmbracoContext.ContentCache.GetById(1234);
return View(somePublishedContent);
}
}
}
UmbracoContextFactory vs UmbracoContext
When is it appropriate to inject the UmbracoContext and when would it be appropriate to inject the UmbracoContextFactory?
I am looking for documentation on the intended use case for each of these classes. For example, when writing a service that gets content data for a surface controller, what would be the correct class to inject?
Hi Chad
There is some work in progress documentation taking shape here that might help:
https://github.com/umbraco/UmbracoDocs/compare/v8/ServicesPattern?short_path=cf2726d#diff-cf2726d2ea2b6f60e0225ce051876a55
Essentially in some places in Umbraco where you might want to inject a custom service of your own creation, the UmbracoContext is not guaranteed to exist, and you would get a boot error - eg a Component or ContentFinder - here therefore if you need to access the Umbraco published Cache you would inject the UmbracoContextFactory and wrap a call to EnsureUmbracoContext in a using statement, to get reference to the content cache - there is an example in the link above.
If you are inheriting from one of Umbraco's special base classes, eg RenderMvcController, SurfaceController, UmbracoApiController
then you already have access to the UmbracoContext, via the 'UmbracoContext' property that they all expose.
eg
(the injection is done for you!)
regards
marc
is working on a reply...