user2653400
user2653400

Reputation: 11

Unity: No parameterless constructor defined for this object

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?

Upvotes: 1

Views: 1633

Answers (1)

Steven
Steven

Reputation: 172835

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.

Upvotes: 1

Related Questions