Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StructureMap and ASP .Net Web API and .Net Framework 4.5

Does the current version of StructureMap support ASP .Net Web API, MVC 4 and .NET Framework 4.5?

like image 774
user1489941 Avatar asked Aug 09 '12 17:08

user1489941


1 Answers

As outlined here, the web API uses a dependency resolver.

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

    public object GetService(Type serviceType)
    {
        return ObjectFactory.GetInstance(serviceType);
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return ObjectFactory.GetInstances(serviceType);
    }

    public void Dispose()
    {
    }
}

And in your Global.asax.cs, include this line to register the dependency resolver:

GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver();

Aside from that, the new Web API is very easy to use with IoC containers.

I haven't looked into it yet, but I believe the BeginScope method that I left blank can be used with child containers.

Edit:

The above implementation works great; in fact I prefer it over the alternative I'm about to tell you. This one will resolve any Type to the best of StructureMap's abilities and will throw errors whenever something goes wrong. I like seeing errors because they show me what I did wrong.

However, the API expects that GetService will return null if something goes wrong. So to be compliant with the API, this is the recommended implementation:

public object GetService(Type serviceType)
{
    if (serviceType.IsAbstract || serviceType.IsInterface)
        return ObjectFactory.TryGetInstance(serviceType);
    else 
        return ObjectFactory.GetInstance(serviceType);
}

The difference is that TryGetInstance only looks for types registered in the container and will return null if something goes wrong. serviceType.IsAbstract || serviceType.IsInterface is considered good enough of a check to decide which method to use. My original answer was intended to be straightforward and simple, but @PHeiberg points out in the comments here that it wasn't entirely "correct". Now that you have knowledge, use whatever seems best.

like image 99
kelloti Avatar answered Oct 15 '22 09:10

kelloti