开发者

How to enable Dependency Injection for ServiceRoute in MVC3 and WCF Web API

开发者 https://www.devze.com 2023-03-21 12:28 出处:网络
I am creating a MVC3 website that will expose a REST API using WCF Web API. To register routes to the REST API I add code to the Global.asax similar to the code below.

I am creating a MVC3 website that will expose a REST API using WCF Web API.

To register routes to the REST API I add code to the Global.asax similar to the code below.

routes.MapServiceRoute<RelationsService>("relations");

This works well enough but i need to use a DI approach to inject the dependencies that the Service depends on. As you can see in the code above the MVC framework is creating the instance of the RelationsService but this should be done by the DI container.

Does anyone know how to co开发者_开发问答nfigure MVC3 so that my own DI container is used for creating the instances of the Services?


You have to extend your current service registration call with an IHttpHostConfigurationBuilder that has been created with an IResourceFactory.

var configurationBuilder = HttpHostConfiguration.Create()
    .SetResourceFactory(new ResourceFactory());

routes.MapServiceRoute<RelationsService>("relations", configurationBuilder);

Then if you for instance use StructureMap as preferred IoC/DI tool you can just ask for the service in the GetInstance method.

public class ResourceFactory : IResourceFactory
{
    public object GetInstance(Type serviceType, InstanceContext instanceContext, HttpRequestMessage request)
    {
        return ObjectFactory.GetInstance(serviceType);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消