Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First try StructureMap and MVC3 via NuGet

I'm trying to figure how to config StructureMap for ASP.NET MVC3 I've already using NuGet and I notice that it creates App_Start Folder with a cs file named as StructuremapMVC, so I check it and notice that is the same code but simplified that will be written manually on App_Start section placed on Global.asax...

This is my code from IoC Class

public static class IoC
    {
        public static IContainer Initialize()
        {
            ObjectFactory.Initialize(x =>
                        {
                            x.Scan(scan =>
                                    {
                                        scan.TheCallingAssembly();
                                        scan.WithDefaultConventions();
                                        scan.AddAllTypesOf<IController>();
                                    });
                            x.For<OpcionDB>().Use(() => new DatabaseFactory().Get());
                        });
            return ObjectFactory.Container;
        }
    }

My Question is Why I get an Exception when I inject some IoC on my Controllers as the follow (I use this pattern : Entity Framework 4 CTP 4 / CTP 5 Generic Repository Pattern and Unit Testable) :

        private readonly IAsambleaRepository _aRep;
        private readonly IUnitOfWork _uOw;

        public AsambleaController(IAsambleaRepository aRep, IUnitOfWork uOw)
        {
            _aRep = aRep;
            this._uOw = uOw;
        }

        public ActionResult List(string period)
        {
            var rs = _aRep.ByPeriodo(period).ToList<Asamblea>();

            return View();
        }

Exception showed :

Exception Details: System.MissingMethodException: No parameterless constructor defined for this object.
like image 523
Jonathan Escobedo Avatar asked Mar 16 '11 00:03

Jonathan Escobedo


2 Answers

To handle parameters in the controller's constructor, the dependency resolver must be configured.

Check the following post on how to wire up the StructureMap with ASP.NET MVC3:

http://stevesmithblog.com/blog/how-do-i-use-structuremap-with-asp-net-mvc-3/

http://codebetter.com/jeremymiller/2011/01/23/if-you-are-using-structuremap-with-mvc3-please-read-this/

like image 190
codeprogression Avatar answered Sep 28 '22 14:09

codeprogression


You are getting that error because you haven't setup StructureMap to resolve the dependencies needed to contruct the AsambleaController so it tries to find a parameterless constructor which there isn't one.

So what you need to do is setup StructureMap for IAsambleaRepository and IUnitOfWork.

On a side note, I'd say that IUnitOfWork should be a dependency on your repository and not your controller... your controller shouldn't need to know about the unit of work.

like image 39
Charlino Avatar answered Sep 28 '22 12:09

Charlino