Examples of ASP.Net MVC 2 - WCF/WSDL - using IoC methodology - asp.net-mvc

We here at my company are just about to get going on ASP.Net MVC 2 for our UI to interface a backend totally SOA with WCF/WSDL. I have looked at various books examples of how to totally make the applicalion loosely coupled from the Domain perspective using the IoC containers e.g. Unity or Castle (looks to be the way to go !) ...BUT Are there any GOOD examples though of this in using WSDL calls ...we are not yet using oData...just the standard wsdl.
Any help, hints appreciated...

The reference application for asp.net mvc NerdDinner is a good place to start http://weblogs.asp.net/shijuvarghese/archive/2009/03/12/applying-dependency-injection-in-asp-net-mvc-nerddinner-com-application.aspx

The Service Contract for each of the WCF services for which you do an "Add Service Reference" will be an interface. Simply program against that interface.
So you have a ISomeService service contract. Pass an instance of that contract to the classes that need to interact with it:
public SomeClass(ISomeService service)
{
this._service = service;
}
public List<Something> GetSomething()
{
return _service.GetSomething();
}
Now you can either pass a SomeServiceClient instance, or a SomeMockService instance to the class.

Related

Asp.Net MVC Consuming a web api from a Class Library

I am wondering if there is a way to create a class library that contains web API, so I can use the dll as a plug-in, to inject into the MVC application.
Thank you in advance for your help.
Web API methods are called over HTTP, so calling a Web API service requires it to be hosted somewhere and called using a suitable client as detailed in #David's link. You can self-host Web API, so in theory you could have an assembly local to an MVC application which contained a class which set up and then called a self-hosted Web API service.
You would inject the Web API service behind an interface, something like this:
public interface IProductsService
{
IEnumerable<Product> GetAllProducts();
}
...implemented something like this:
public class SelfHostedWebApiProductsService
{
public SelfHostedWebApiProductsService()
{
// Set up a self-hosted Web API service
}
public IEnumerable<Product> GetAllProducts()
{
// Call your self-hosted WebApi to get the products
}
}
Configure your DI container to use SelfHostedWebApiProductsService for the IProductsService interface, and away you go. This article details how to set up and call a self-hosted Web API.
As the SelfHostedWebApiProductsService sets up the self-hosted Web API in its constructor - a relatively expensive operation - you might want to consider giving this class a singleton lifetime in your DI container.
You could Self-Host a Web API:
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/self-host-a-web-api
You can put all your controllers in a Class Library project.
Then use Autofac to resolve the dependencies in your host project:
https://code.google.com/p/autofac/wiki/WebApiIntegration

How do I get Unity to inject a reference to HttpSessionState to a service

Disclaimer: I have a fair bit of experience with DI containers but am quite new to Unity.
I have an MVC project that is all wired up with Unity DI using constructor injection and works great. But I now have a service that I want to inject into my controllers (and maybe places other than controllers at some point) and this service needs access to ASP.NET session state. The service's purpose is to manage a list in session and I don't want the list mechanics in my controller.
I realize I could add a Setup method to the service (and it's interface) that my controller could call, passing in a reference to the Session, before using the service, but I don't like that as I may want to make an implementation of the service that uses something other than Session for my state management and also it is implementation specifics leaking into my interface. I also realize I can use HttpContext.Current in my service but I don't want to do that for many reasons, particularly for the issues it creates for unit testing.
Can Unity inject a reference to HttpSessionState into the service's constructor?
There's a couple ways to do this. The easiest is probably to use an injection factory:
container.RegisterType<HttpSessionState>(
new InjectionFactory(c => { return HttpContext.Current.Session; }));
Then anywhere you have a dependency on the HttpSessionState in the graph, the delegate given will run and pull it out of HttpContext.Current.
Of course, this only works if you're doing a new resolve per request.

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

Firstly - I'm not asking this question How to host a web service in MVC3? I know where the 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)
{
// ...
}

ASP.NET MVC consuming WCF

My ASP.NET MVC 2 controllers are currently instantiating service objects in their constructors by passing repository instances that are instantiated by Castle Windsor. I have unit tests that call the controller actions after passing Moq instances of the repositories to the controller's constructor.
I want to allow a third-party UI to access these service objects through WCF.
It occurred to me that converting my existing Service layer into Web services or even adding a new Web service layer between the UI and the existing Service layer will break my unit tests unless I find a way to bridge that gap.
I was trying to work out a solution where my UI was coded against an interface of the service layer (it already is) and I could use DI to pass the Web service implementation at run-time and pass the existing implementation during unit testing. The Web service implentation would simply call the existing implementation.
Questions:
Is such an approach advisable / possible?
Are there any examples of this in a tutorial or open source project?
EDIT:
I believe I have a workable solution now thanks to the suggestions below. I created a WCF Service Application that uses the existing service interfaces from my domain model. The WCF implementation is a class where the constructor takes repository instances from Ninject's WCF extension and creates an instance of the service from the domain model. Each method/function in WCF simply calls the same method/function from the existing service layer.
There were some caveats. For example, I can no longer pass a reference to my ASP.NET MVC ModelState when I create the service in the controller (actually, I use Ninject to create an instance of the WCF service and supply that to the controller's constructor). The reason is that WCF is a messaging platform - changes must be explicitly communicated back with each call (i.e. my validation errors are now communicated back as reference parameters on individual functions/methods).
I also had to add some serialization/servicemodel references to my formerly POCO Core project.
Also, I switched from Castle to Ninject because Castle's WCF solution has a maturity level of low and I wasn't comfortable using that at this time.
Can you explain in more detail why your tests would break?
I do this type of development all the time. Services as classes => services as WCF services.
Your tests shouldn't break. A WCF Service is almost 100% contract, the underlying business code and logic shouldn't have to change.
Check out the Web Services Software Factory created by the Patterns & Practices team. It is a good way to structure your services into contract projects (data, message, service) and "business code". Once you get a better understanding of how to structure your code, you can refactor their style to something that fits you a little better. Their example tends to separate everything into lots of VS projects, which can be a little overkill for most shops. Example, I don't see many shops sharing data contracts across projects. Yes, in a perfect world, you should probably share a lot os types (like address) across projects, but I don't see it done very often. So, I tend put all my contract stuff in one VS project.
If your services are already defined as interfaces then you've got a head start.
Pass the services into the controllers as constructor dependencies, rather than the repositories. Let your DI container A) provide the repositories to the services, and B) provide the services to the controllers.
If you want to stand up your service layer as wcf services to be accessed by other applications, you'll want to use the wcf service factory to pull the concrete service implementations out of your DI container. Here's an example with windsor, it should be easy to adapt to whatever container you use.
At this point you can modify your website to either A) continue to invoke the services directly, or B) have them call back to the web services using service clients. There are pros and cons to both methods.

SOA Architecture with WCF + IOC Structuremap

I'm a little new to DI containers like StructureMap and I've been using it for a short time with asp.net mvc applications. Now I'm splitting my architecture that will have a WCF service layer and a sort of consumers like ASP.NET MVC app, Silverlight App, And Winfors/WPF App. When using SM with asp.net mvc I've been initializing the IOC by the app startup of the asp.net mvc, now, using for many project I can't think a good place where the IOC config should be located.
I want to make DI in the services layer too(injecting Repositories).
In this scenario, where I do load my IOC config and how I'll use across the projects(like the controller factory is needed only in the asp.net mvc app)?
You create and configure a container per application.
If you have an ASP.NET MVC site, you create and configure a container instance in Global.asax.
In a WCF service you can write a custom ServiceHostFactory that spins up a custom ServiceHost that again attaches an appropriate IInstanceProvider that uses a container instance to wire up the WCF service. That sounds complicated, and it definitely is more complicated than it ought to be. I have previously touched on this subject in a completely different context, but this blog post should give you some hints - particularly if you keep in mind that delegates are anonymous interfaces.

Resources