1

I have started a Web API project, and extended it to also be a normal MVC project. By this I mean I have some controllers deriving from ApiController and others from Controller.

Here's my DependencyResolver:

public class StructureMapDependencyResolver :IDependencyResolver
{
    public IDependencyScope BeginScope()
    {
        return this;
    }

    public StructureMapDependencyResolver(IContainer container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
        if (serviceType.IsAbstract || serviceType.IsInterface)
            return _container.TryGetInstance(serviceType);

        return _container.GetInstance(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.GetAllInstances<object>()
                         .Where(s => s.GetType() == serviceType);
    }

    private readonly IContainer _container;

    public void Dispose() { }
}

and here's my Global.asax.cs:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ObjectFactory.Initialize(x =>
        {
            x.For<IDataService>().Use<MockDataService>();
        });
    ObjectFactory.Configure(x => x.Scan(scan =>
        {
            scan.AssembliesFromApplicationBaseDirectory();
            scan.LookForRegistries();
            scan.TheCallingAssembly();
            scan.WithDefaultConventions();
        }));

    var container = ObjectFactory.Container;
    GlobalConfiguration.Configuration.DependencyResolver = 
               new StructureMapDependencyResolver(container);
}

The Web API controllers are working great, but I can't get constructor injection to work in the Controller-derived ones. It's the usual No parameterless constructor defined for this object error message of course.

I'm at a bit of a loss here... this is my first foray into Web API so I'm not sure where I'm going wrong.

1 Answer 1

2

You need to call the DependencyResolver.SetResolver to your MVC IOC container. Make sure your container implements MVC's IDependencyResolver as well, otherwise it won't work for MVC.

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.