SaphuA
SaphuA

Reputation: 3150

StructureMap with MVC and multiple layers

I am using StructureMap.MVC5 and have the following projects and classes:

Web
    HomeController(PageService pageService)
Services
    PageService(IPageRepository pageRepository)
Repositories
    PageRepository : IPageRepository
IRepositories
    IPageRepository

With the default implementation of StructureMap.MVC5 it automatically resolves the PageService into my HomeController, but not PageRepository into my PageService. This gives me the exception: No parameterless constructor defined for this object.

This is solved by adding a line to DefaultRegistry:

For<IPageRepository>().Use<PageRepository>();

But obviously I would rather have StructureMap automatically resolve this. Is there a way to achieve that?

This is what the DefaultRegistry looks like:

public DefaultRegistry()
{
    Scan(scan =>
    {
        scan.TheCallingAssembly();
        scan.WithDefaultConventions();
        scan.With(new ControllerConvention());
    });
}

Upvotes: 1

Views: 87

Answers (1)

Joseph Woodward
Joseph Woodward

Reputation: 9281

The reason your repository isn't being resolved automatically is because it's in another assembly, where as your service is being referenced within your controller, meaning it gets resolved by the TheCallingAssembly call.

To tell StructureMap to load your repositories you have to explicitly tell it which assembly to scan:

scan.AssemblyContainingType<IPageRepository>();

The type specified doesn't have to be a IPageRepository type, just some type within your repository assembly so StructureMap knows where to look.

Now any types within your repository assembly should be resolved automatically.

Upvotes: 1

Related Questions