Copied to clipboard

Flag this post as spam?

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


  • Dave Hobbs 2 posts 83 karma points
    Jan 18, 2018 @ 11:15
    Dave Hobbs
    0

    Using Autofac - how to inject / use DatabaseContext

    I've started using Autofac and separated my "services" with the goal I can write unit tests. Some services need to access custom DB tables. What's the best practice for accessing / using the Umbraco DBContext?

    I have something like: enter image description here

    But obviously that's not going to be right for unit tests? Do I need some kind of factory / wrapper. Does anyone have any examples of how to do this?

    Thanks in advance, Dave

  • Tom Steer 161 posts 596 karma points
    Jan 18, 2018 @ 13:13
    Tom Steer
    100

    Hi Dave,

    You should just need to register the DatabaseContext with Autofac container and then put it as a parameter to your constructor.

    builder.Register(ctx => ApplicationContext.Current.DatabaseContext).ExternallyOwned();
    

    Cheers,

    Tom

  • Dave Hobbs 2 posts 83 karma points
    Jan 19, 2018 @ 11:38
    Dave Hobbs
    1

    Hi Tom,

    Brilliant - thanks! That seems to work though I'll confess I'm lost how it's injecting it!

    To anyone who finds themselves here it just then needed injecting as

    public ClientsDataRepository(DatabaseContext databaseContext)
            {
                //todo: this is not great?! needs a wrapper so I can inject it? 
                //_db = ApplicationContext.Current.DatabaseContext.Database;
                _db = databaseContext.Database;
            }
    
  • Martin Griffiths 826 posts 1269 karma points c-trib
    Dec 30, 2020 @ 14:22
    Martin Griffiths
    0

    Hi Dave

    Can you provide a little more context into how you used this?

    Martin

  • 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