0

I have a little experience working with Dependency Injection using Xamarin.Forms, but not in WebApi, What I want is send data through my Interface and execute inside of my Class which is implementing that Interface, there's what I have :

public interface IRepository
{
    IHttpActionResult SendContext(user user);
    IHttpActionResult GetContextData(int id);
}

public class ContextGoneBase : ApiController,IRepository
{
    public  IHttpActionResult GetContextData(int id)
    {
        try
        {
            using (var context = new GoneContext())
            {
                var result = context.user.Where(a => a.id_user == id).Select(w =>
                new { w.user_name, w.cellphone_number, w.user_kind, w.CEP, w.area.area_name, w.district, w.city.city_name, w.city.state.state_name });
                var list = result.ToList();

                if (list != null)
                {
                    return Ok(list);
                }
                else
                {
                    return BadRequest();
                }
            }
        }
        catch (Exception)
        {
            return BadRequest();
        }
    }

And Inside of my controller I was trying to do something like that:

[Route("86538505")]
    public IHttpActionResult GetData(int id, IRepository repo)
    {
        this._repo = repo;
        var result = _repo.GetContextData(id);
        return result;
    }

But, it fails! Thanks!

1 Answer 1

0

You should instead pass the IRepository as a parameter to the constructor Set the field _repo of type IRepository to the value of the parameter passed.

public ContextGoneBase (IRepository repository){ //Constructor

  _repo = repository; 

}

.And then use an IOC container like Unity to instantiate the controller with the right parameters.For example after you install Unity using nuget you will have a UnityConfig class file and there you can register your repository type.For example if your repository is of type Repository then

 public static class UnityConfig
        {
            public static void RegisterComponents()
            {

// register all your components with the container here
            // it is NOT necessary to register your controllers

            // e.g. container.RegisterType<ITestService, TestService>();
                var container = new UnityContainer();
                container.RegisterType<IRepository,Repository>();

                GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
            }
        }

Now in Global.asax call this method:

 protected void Application_Start()
        {

            UnityConfig.RegisterComponents();

        }

Your Answer

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