1

I've set up a very simple dependency resolver but it is not being called for my controllers.

when I hit the HomeController GetService is called:( http:localhost:xxxx/) but (http://localhost:xxxx/api/Customers) it isn't.

In Global.asax I've put in Application_Start

        DependencyResolver.SetResolver(new PoorMansResolver());

and my resolver class is

  public class PoorMansResolver : IDependencyResolver
    {
        static readonly ICustomerRepository CustomerRepository = new CustomerRepository();

        public object GetService(Type serviceType)
        {
            if (serviceType == typeof (CustomersController)) 
                return new CustomersController(CustomerRepository);
            else return null;
        }

        public IEnumerable<object> GetServices(Type serviceType)
        {
            return new List<object>();
        }
    }

Why is the resolver not being called?

3 Answers 3

12

Have you set the Resolver for both MVC4 and WebAPI?

This sets it for mvc (System.Web.Mvc):

DependencyResolver.SetResolver(new PoorMansResolver()); 

BUT this sets it for Web API (System.Web.Http):

GlobalConfiguration.Configuration.DependencyResolver = new PoorMansResolver();
Sign up to request clarification or add additional context in comments.

3 Comments

Wow... that's horrible duplication
Haha, yep. It's the same with other parts of the stack too, including routes
@JohnnoNolan See also this post, for an opinion on why you shouldn't mix them.
1

The dependency resolvers for WebAPi and MVC Controllers are in different namespaces. You'll have to implement a resolver for the two resolvers and assign them to mvc controllers and web api controllers seperately like below in the ninjectwebcommon.cs file

    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);

        DependencyResolver.SetResolver(new NinjectDependencyResolver());
        GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);
        return kernel;
    }

NinjectDependencyResolver implements System.Web.Mvc.IDependencyResolver for MVC Controllers while NinjectResolver implements System.Web.Http.Dependencies.IDependencyResolver for WebApi Controllers.

Comments

0

I'd be concerned with how/if you are wiring up your ControllerFactory. See this SO question. It's about Unity but the principle is the same.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.