Copied to clipboard

Flag this post as spam?

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


  • nickornotto 397 posts 900 karma points
    Jun 22, 2017 @ 11:24
    nickornotto
    0

    Use of ApplicationContext in repository/ services

    I am trying to put DatabaseContext into the repository and use with petapoco querying and updating

    I created the following:

    public class MyRepository : IMyRepository
    {
        private Database Database => UmbracoContext.Application.DatabaseContext.Database;
    
        public List<MyModel> GetItems()
        {
            return Database.Query<MyModel>($"SELECT * FROM Items").ToList();
        }
    }
    

    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

  • Dan Diplo 1554 posts 6205 karma points MVP 5x c-trib
    Jun 22, 2017 @ 11:39
    Dan Diplo
    0

    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.

  • nickornotto 397 posts 900 karma points
    Jun 22, 2017 @ 12:07
    nickornotto
    0

    Great thank you. And what's the best way to use it in a surface controller?

  • Dan Diplo 1554 posts 6205 karma points MVP 5x c-trib
    Jun 22, 2017 @ 12:31
    Dan Diplo
    101

    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.
        }
    }
    
  • nickornotto 397 posts 900 karma points
    Jun 22, 2017 @ 14:24
    nickornotto
    0

    Thank you!

Please Sign in or register to post replies

Write your reply to:

Draft