Copied to clipboard

Flag this post as spam?

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


  • Matt 3 posts 83 karma points notactivated
    Jul 06, 2020 @ 15:19
    Matt
    0

    Database access in static class with DI

    Hello,

    In Umbraco 7 our system made use of custom static helper classes, which used ApplicationContext.Current.DatabaseContext.Database for database access. With DI in Umbraco 8 however, from what I understood we are supposed to access the database using an IScopeProvider.

    The problem here is that if I keep the helper classes static my project won't build, since I'm using the constructor pattern to inject the scopeProvider. For example:

    public class customHelper {
    
        private readonly IScopeProvider _scopeProvider;
    
        public customHelper(IScopeProvider scopeProvider)
        {
            _scopeProvider = scopeProvider;
        }
    
        public object getItem()
        {
            using (var scope = _scopeProvider.CreateScope())
            {
                var item = scope.Database.FirstOrDefault(...);
                scope.Complete();
                return item;
            }
        }
    }
    

    If I want to use this helper in my views I need to instatiate it, howerer here I don't have access to the scopeProvider and thus I cannot instantiate and use my helper classes.

    Do you maybe have any ideas on how to deal with this? Maybe a way to keep the helper static, or a way to instatiate it within a view.

    Thanks!

  • Joep 90 posts 688 karma points
    Jul 07, 2020 @ 08:24
    Joep
    100

    Hi,

    You can just use the Umbraco.Web.Composing.Current.ScopeProvider to get the scopeprovider inside the static class. Or you can create you're own ViewPage, where you can just call the service in you're view https://our.umbraco.com/documentation/Implementation/Services/#using-the-siteservice-inside-a-view .

    -Joep

  • Matt 3 posts 83 karma points notactivated
    Jul 13, 2020 @ 07:26
    Matt
    0

    Thanks, this seems to work! :-)

    Do you know if there is a difference between Umbraco.Web.Composing.Current and Umbraco.Core.Composing.Current ? They seem to do the same.

  • Nik 1413 posts 6212 karma points MVP 3x c-trib
    Jul 07, 2020 @ 11:59
    Nik
    0

    Hi Matt,

    I would agree with Joep's second option of the custom view page class and allowing DI to inject the required classes in.

    Also, you can register your helper with the DI container so it can pass that in as well so you don't have to create your own instance :-)

    Nik

  • 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.

Please Sign in or register to post replies