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.
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:
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!
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
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.
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
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.