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:
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?
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;
}
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:
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
Hi Dave,
You should just need to register the DatabaseContext with Autofac container and then put it as a parameter to your constructor.
Cheers,
Tom
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
Hi Dave
Can you provide a little more context into how you used this?
Martin
is working on a reply...