开发者

design pattern for adding a web service in ASP.NET MVC3

开发者 https://www.devze.com 2023-02-15 08:21 出处:网络
Firstly - I\'m not asking this question How to host a web service in MVC3? I know where t开发者_开发知识库he button is :-)

Firstly - I'm not asking this question How to host a web service in MVC3? I know where t开发者_开发知识库he button is :-)

I'm trying to find an example of best practices of how to use the new DI / Common Service Locator framework in order to make web service calls (and code dependent on web service calls) testable. I've no experience of using NInject or the like - is that the way to go?


Pretty much the same way one deals with any external depenency -- wrap it up in an interface, make the controller take an instance of the interface as a constructor parameter. Implementation-wise, you can handle things a number of ways, we have typically made the service wrapper take the service as a dependency and let structuremap worry about lifecycle. Not horribly familiar with NInject so I'm not sure if there is a better way there but I'd suspect they have similar capabilities.


I don't know what is the best practice but I think you can do this with Windsor's WCF facility (Ninject has a WCF extension as well). Register your service, then set your dependency resolver and let MVC's dependency resolver to do the hard work, constructor injection for example:

Register your service:

container = new WindsorContainer().AddFacility<WcfFacility>();

container.Register(Component
    .For<IService>()
    .On(WcfEndpoint.FromConfiguration("...")))
    .LifeStyle.Transient);

Set dependency resolver:

DependencyResolver.SetResolver(new WindsorDependencyResolver(container));

Then MVC3's new dependency resolver should be able to inject your service proxy into the constructor, for example:

public HomeController(IService service)
{
    // ...
}
0

精彩评论

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

关注公众号