Generally you want to pass in services to your repository via the constructor - this decouples them. You also want to use the UmbracoDatabase object for PetaPoco, accessible from ApplicationContext. A nice way to do this would be something like:
public class MyRepository : IMyRepository
{
private readonly UmbracoDatabase Database;
public MyRepository(UmbracoDatabase database)
{
this.Database = database;
}
public MyRepository() : this (ApplicationContext.Current.DatabaseContext.Database)
{
}
public List<MyModel> GetItems()
{
return Database.Query<MyModel>($"SELECT * FROM Items").ToList();
}
}
Using this you can either pass in the database to the constructor or just use the default constructor to initialise the database from the ApplicationContext.Current singleton that Umbraco exposes.
In a surface controller you could just instantiate your repo in the constructor and then you can access it any method. Something like:
public class MySurfaceController : SurfaceController
{
private MyRepository repository;
public SchoolProfileFormSurfaceController()
{
this.repository = new MyRepository(ApplicationContext.DatabaseContext.Database);
}
public ActionResult DoSomething()
{
var data = this.repository.GetStuff();
// etc.
}
}
Use of ApplicationContext in repository/ services
I am trying to put
DatabaseContext
into the repository and use with petapoco querying and updatingI created the following:
It returns an error though:
Cannot access non-static property Application in static content
How to use
ApplicationContext
then in repository or services class?Thanks
Generally you want to pass in services to your repository via the constructor - this decouples them. You also want to use the
UmbracoDatabase
object for PetaPoco, accessible fromApplicationContext
. A nice way to do this would be something like:Using this you can either pass in the database to the constructor or just use the default constructor to initialise the database from the
ApplicationContext.Current
singleton that Umbraco exposes.Great thank you. And what's the best way to use it in a surface controller?
In a surface controller you could just instantiate your repo in the constructor and then you can access it any method. Something like:
Thank you!
is working on a reply...