I recently started with TDD and dependency injection. This is one BIG Mindset change, and i am still trying to puzzle together all the pieces.
I have a service layer for all the business logic to keep the controllers as thin as possible.Some of the services in my service requires HttpContext. What would be the best way to create the service so that unit testing can be done as well.
Currently i have a ServiceBase that looks like this
public class HttpContextService
{
private HttpContextBase _ServiceContext;
public HttpContextBase ServiceContext
{
get
{
if (_ServiceContext == null)
_ServiceContext = new HttpContextWrapper(HttpContext.Current);
return _ServiceContext;
}
set { _ServiceContext = value; }
}
}
So this means that all my services can just inherit from this service. The reason i created a property for the HttpContextBase is so that I can set it, when unit testing the service. 1. Is there any way to rather inject the HttpContext into the service in Unity Bootstrap file. ? 2. Is this the right approach or am i missing something ?
thanks in advance. Like i said, i am struggeling to get my head around this whole TDD Dependency injection way of coding.
Some of the services in my service requires HttpContext
Your services should live in the business layer and this layer should have no notion of the presentation technology you use. This allows you to reuse this logic for different technologies (such as WCF web service, or Windows Service). But even if you don't intend to reuse this code, tightly coupling your service to the HttpContextBase
still increases complexity, and makes it harder to unit test, as you are already experiencing.
The solution is to abstract the things you want from the HttpContextBase
behind abstractions, and not an abstraction over the complete HttpContext
, but over the individual functionality that you want to use in a certain case.
For instance, when you want to access the HttpContextBase.User
property, you'd be better of with the following abstraction:
public interface IUserContext
{
IIdentity Current { get; }
}
This makes testing easier, your services simpler and makes creating different implementations for different applications simpler.