0

I am doing an MVC 5 with API2 Controller Application.

I have a Controller that call an ApiController in the same project. In my Api Controller Method I want to use DI.

It looks like this.

        [ActionName("Method1")]
        [HttpPost]
        public int Method1(long User_id)
        {
            long user_id = Newtonsoft.Json.JsonConvert.DeserializeObject<long>(User_id.ToString());
            IContactRepository _contactRepository = DependencyResolver.Current.GetService<IContactRepository>();
            return _contactRepository.Get_CountMensajeByUser(user_id);
         
        }

In order to use

[ActionName("RetProduct")] and [HttpPost]

I have to include using System.Web.Http; reference

But, in the other hand, in order to use DependencyResolver I have to include

using System.Web.Mvc;

when I include that reference, System.Web.Http; does not work.

Another alternative is to set de DI in the API Controller Constructor like this

  private IContactRepository _sessionRepository;
        public ApiController(IContactRepository contactRepository)
        {
            _contactRepository = contactRepository;
           
        }

So i avoid to use DependencyResolver. But I have to use Parameters in the Controller Constructor. On my controller where I call Api controller like this.

 var webApi = new APIController();
                model.CantMensajeByUser = webApi.CountMensajeByUser(10);

Where I am not using parameters.

What is the correct way to do it?

1
  • You are confusing the concept. The first snippet you suggested used Service Locator anti-pattern. Explicit constructor injection is the way to go but there is no needs to create the ApiController within the Controller. Just have the functionality in a service and inject the service into the Controller. If the web API shares the same project as the MVC Controller then DRY, reuse the services. Commented Aug 4, 2017 at 18:13

1 Answer 1

1

I think an easier solution for the problem you are trying to solve is to use an actual IoC container. For C#.NET in particular, Ninject is very easy to use and the best part is that you can resolve all of your dependencies in one file rather than doing that inside of your business logic.

I encourage you to check out http://www.ninject.org/.

Sign up to request clarification or add additional context in comments.

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.