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 84 karma points notactivated
    Jul 06, 2020 @ 15:19
    Matt
    1

    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 96 posts 698 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 84 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 1591 posts 7148 karma points MVP 6x 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

Please Sign in or register to post replies

Write your reply to:

Draft