Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at

  • Rosa 8 posts 88 karma points
    7 days ago

    Umbraco 10 Views and Dependency Injection - best practice?

    Can someone explain to me how/why dependency injection is used in Views in Umbraco 10 (and I assume 9)?

    Why are we not able to access the UmbracoHelper by default, for example?

    I am currently doing this to get access to the Umbraco Helper:

    @inject IUmbracoHelperAccessor umbracoHelperAccessor
    @inherits UmbracoViewPage<BlockListItem>
        var row = (RoleInsightsCarousel)Model.Content;
        var settings = (RoleInsightsCarouselSettings)Model.Settings;
        if (settings != null && settings.DisableComponent) return;
        var roleInsightPages = new List<RoleInsightsPage>();
        if (umbracoHelperAccessor.TryGetUmbracoHelper(out var umbracoHelper))
            if (umbracoHelper != null)
                roleInsightPages = umbracoHelper.GetRoleInsights(row.RoleTypes);

    GetRoleInsights() is an extension method I have created btw.

    In another partial I need the context and could only get it by injecting in the IUmbracoContextAccessor and then calling contextAccessor.TryGetUmbracoContext(out var umbracoContext)

    Is there a better way? Any explaination for how this works would be much appreciated!

  • Jamie Attwood 189 posts 474 karma points c-trib
    6 days ago
    Jamie Attwood

    You should not have to use DI in your views to get at UmbracoHelper.

    As long as your page inherits from Umbraco.Cms.Web.Common.Views.UmbracoViewPage you should be able to access it directly by using @Umbraco.

    I am not sure if your entire view header is shown in your code example, but if you are not able to access @Umbraco methods, you can try something like (Umbraco 10):

    @inherits Umbraco.Cms.Web.Common.Views.UmbracoViewPage<Umbraco.Cms.Core.Models.Blocks.BlockListModel>
  • Jamie Attwood 189 posts 474 karma points c-trib
    6 days ago
    Jamie Attwood

    Really though, ideally you should be creating a custom controller and view model for each of your views (either based on document type or template name). This was you can simplify or eliminate business logic from your views.

    Have you looked into Umbraco route hijacking? Check out:

    And make sure you check out "Returning a view with a custom model" that outlines a way you can create a view model that inherits from your modelsbuilder model that will allow you to add view specific properties that may not be available in your modelsbuilder models.

Please Sign in or register to post replies

Write your reply to: