1

I'm using Unity Application Block together with UnityMvc. I have a controller named HomeController that has an action:

    public ActionResult Add(UnitOfWork UnitOfWork)
    {
        Person p = new Person();
        p.Code = "1202";
        p.City = new City() { Code = "21", Name = "Paris" };
        UnitOfWork.Save();

        ViewBag.Message = "Done.";

        return View();
    }

UnitOfWork parameter has a constructor like this:

    public UnitOfWork(Context Context)
    {
        this.context = Context;
    }

and a "Save" Method:

    public void Save()
    {
        this.context.SaveChanges();
    }

When unity tries to construct UnitOfWork Object for "Add" action it produces the following error:

No parameterless constructor defined for this object.

It seems as UnitOfWork is a parameter itself for "Add" action, it should have a parameterless constructor.

Is it true or any body has a solution?

3
  • Please show your constructor. Also note that you normally can't and shouldn't inject services through the action methods. You should use the constructor instead. Commented Aug 5, 2013 at 16:03
  • Yes, the problem was the absense of the constructor. Model binder is responsible for constructing action parameter objects. Commented Aug 7, 2013 at 6:39
  • You can write your custom ModelBinder in order to create a type that don't have parameterless constructor. Commented Aug 7, 2013 at 7:11

1 Answer 1

1

MVC model binding takes care of injecting values into action methods. Without the registration of a specially crafted custom model binder, Unity (or any DI container for that matter) will not inject services into action methods.

Unity (and other DI containers) only injects services into the type's constructor and this is the adviced way of doing dependency injection.

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.