1
votes

I am following Onion Architecture for my Web API and AngularJS Project. In the Infrastructure.DependencyResolution part, I am using Simple Injector. Here is my code:

[assembly: PreApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]
namespace Infrastructure.DependencyResolution
{
    public class IocConfig
    {
         private static Container _container;

         public static void RegisterDependencies()
         {
              _container = new Container();

              _container.Verify();

              _container.RegisterWebApiRequest<IEntitiesContext>(() =>
              {
                   return new MyContext();
              });

              _container.RegisterWebApiRequest<IUserRepository, UserRepository>();
              _container.RegisterWebApiRequest<IAccountService, AccountService>();
              _container.RegisterWebApiRequest<IUnitOfWork, UnitOfWork>();

         }
    }
}

Now If I try to put url to go to my account controller, I am getting this error:

An error occurred when trying to create a controller of type 'AccountController'. Make sure that the controller has a parameterless public constructor.

I searched and found out that Simple Injector has some different code for Web Api as suggested by their site Like:

// This is an extension method from the integration package.
container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

I copied that as well but it did not accept GlobalConfiguration.Configuration, I guess because I am using it in a library project.

When I set a break point in the RegisterDependencies method, Visual Studio doesn't stop at the break point.

Can someone show me the way where to go?

1
it did not accept GlobalConfiguration.Configuration What did it accept?Yuval Itzchakov
It means it gave compile time error.Usman Khalid
It just did not recognize library.Usman Khalid
I don't see any relationship between your problem and the Onion archtecture. You might want to rename your question.Steven

1 Answers

5
votes

You are missing is the registration of the SimpleInjectorWebApiDependencyResolver as described in the Web API integration guide:

GlobalConfiguration.Configuration.DependencyResolver =
    new SimpleInjectorWebApiDependencyResolver(container);

Without overriding Web API's default IDependencyResolver, Web API will simply try to instantiate controller instances itself, and this requires controller types to have a default constructor. By replacing this IDependencyResolver with the SimpleInjectorWebApiDependencyResolver requests for controller instances are forwarded to the Simple Injector container.

You will have the most succes when using Simple Injector's Web API Quick Start NuGet package. This will bootstrap your application and allows you to get started quickly.