1

I am having a project where I am using Simple Injector as IoC and inject my dependency into the controller. It works fine

This is my controller:

public class PatientController : BaseController
{
    private IUnitOfWork unitOfWork;

    public PatientController(IUnitOfWork _unitOfWork)
    {
        this.unitOfWork = _unitOfWork;
    }

    ...
}

And this is the Simple Injector Initialization.

namespace MyApp.App_Start
{
    public class SimpleInjectorInitializer
    {
        public static void Initialize()
        {
            //Code for registering our repository class and DI
            var container = new Container();
            container.Register<IUnitOfWork, UnitOfWork>();
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            DependencyResolver.SetResolver(
                new SimpleInjectorDependencyResolver(container));
        }
    }
}

It works like a charm. My concern is how to I test my controller. Before I am having something like this, my constructor is parameterless, how would I change it to fitthe newly design ?

namespace MyApp.App_Start
{
    public class SimpleInjectorInitializer
    {
        public static void Initialize()
        {
            //Code for registering our repository class and DI
            var container = new Container();
            container.Register<IUnitOfWork, UnitOfWork>();

            // This two extension method from integration package
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
            DependencyResolver.SetResolver(
                new SimpleInjectorDependencyResolver(container));
        }
    }
}

Thanks for your helps to pointing out to me the right direction to go.

Cheers all

Steven
  • 166,672
  • 24
  • 332
  • 435
dtjmsy
  • 2,664
  • 9
  • 42
  • 62
  • You should not use your DI container when unit testing. You should create your controller manually with fake dependencies. – Steven Apr 19 '15 at 09:18
  • 1
    You can use NSubstitute to mock the unitOfWork object and instantate the controller inside your unit test passing the mock object in the contructor. See here http://nsubstitute.github.io/ – Paolo Costa Apr 19 '15 at 12:30

0 Answers0