1

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());
    });
}

1 Answer 1

1

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.

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.