ASP.NET MVC, WCF Service, and validation? - asp.net-mvc

My ASP.NET MVC controller constructors create an instance of a service class by supplying it with (among other things) a ModelStateWrapper (similar to this article). Since this object is handled through a reference, any changes made to it in the service are reflected when the controller accesses that ModelStateWrapper object.
I need to convert that logical service layer into WCF services that will be hosted in IIS.
Assuming I want to continue performing validation in the service layer, which approach is better?
Pass the ModelStateWrapper object by reference (possible according to MSDN) with each service operation
Keep track of errors in the service and have the client explicitly retrieve a list of errors after any/all service operations are performed
Any other suggestions or links to articles that would help me perform validation behind a WCF service?
It should be noted that these services will eventually be consumed by a variety of UIs (ASP.NET MVC, Winform, Console, maybe even third-party).

Since you already have everything in place and working, pass the ModelStateWrapper over the wire to WCF service. Let it fill it out and send back.
The other platforms can use this same wrapper to get the error information.

Related

Proper SimpleInjector configuration for WebApi and UnitOfWork Pattern

I have read through the SimpleInjector documentation a few times. But have a few questions.
Context:
3 tier app (presentation (mvc + api controllers), service (business logic), data (repositories, entities, etc)
Unit of Work is a thin wrapper around EF's DbContext
my DbContext and Unit of Work are registered PerWebRequest, using
RegisterWebApiRequest causes an exception, because the Unit of Work is used
outside of Web API requests.
my MVC and Api controllers registered using RegisterWebApiControllers(GlobalConfiguration.Configuration) and RegisterMvcControllers(Assembly.GetExecutingAssembly())
Each controller has one or more services injected into it.
Each service has one or more repositories injected into it.
A service may also have another service injected into it.
I want the same Unit Of Work/DbContext to exist in all my services/repositories.
Questions:
Because I am using services in my MVC controllers as well as API controllers; does that mean I can not use RegisterWebApiRequest in place of RegisterPerWebRequest?
none of my services, repositories, etc, maintain any state, I would get the same functionality using PerWebRequest as Transient; is there any advantage to using PerWebRequest over Transient?
Please read the following q/a: How to configure simple injector container and lifestylse in a MVC web app with WebAPI, WCF, SignalR and Background Tasks. The answer explains that:
Putting your Web API in the same project as your MVC controllers is a bad idea from an architectural perspective.
But if you want to do this, you can use the WebRequestLifestyle in both type of applications. The WebApiRequestLifestyle is meant as lifestyle that works for Web API for both IIS and self-hosted environments, but since you placed the Web API controllers in the same project, you are clearly only interested in IIS-hosted; in that case the WebRequestLifestyle will do just fine.
Because I am using services in my MVC controllers as well as API controllers; does that mean I can not use RegisterWebApiRequest in place of RegisterPerWebRequest?
Both lifestyles use a different way of caching. The WebRequestLifestyle uses the HttpContext.Current.Items dictionary to store its SimpleInjector.Scope instance, while the WebApiRequestLifestyle uses the CallContext class to store the Scope during the lifetime of a single asynchronous operation.
Just as the WebRequestLifestyle can be used while resolving Web API controllers, you can use the WebApiRequestLifestyle (or the underlying ExecutionContextScopeLifestyle) for MVC controllers as well. But if you want this, you will create your own IDependencyResolver implementation for MVC that will explicitly start and end an ExecutionContextScope. The absense of a Scope stored in the CallContext is the reason resolving MVC controllers fails when registering services using the WebApiRequestLifestyle. But while it's possible to use the WebApiRequestLifestyle in MVC, the otherway around is much easier, since no custom code is required.
none of my services, repositories, etc, maintain any state, I would get the same functionality using PerWebRequest as Transient; is there any advantage to using PerWebRequest over Transient?
If services don't have state, it doesn't matter what lifestyle they have. The only restriction is that they have dependencies that have a lifestyle that is equal to or longer than their own. Violating this restriction is called Captive Dependencies and can cause all kinds of trouble. Because captive dependencies are bad, Simple Injector v3 checks and prevents this for you.
Although you can probably make all objects in your configuration scoped (non-transient), making them transient is usually easier to configure, and might result in better performance (although you will probably never notice the difference in real life).

Model v/s Controller - wcf communication

In a typical ASP.net mvc application which layer should talk to WCF service ? Is it model or the controller ? Which approach is benefical ?
Thanks
Josh
Normally that should be the data layer. The controller then talks to the data layer. Whether the data is stored inside a database, flat file or coming from a remote web service, the data layer should be responsible for retrieving and manipulating it. You could then of course have different implementations for the data layer depending on where your data is coming from.
You need to have an abstraction (interface) over the operations you need to perform with the data and then have your Controller take this interface as constructor argument. For the case of WCF, you could directly use the interface that was created for you when you imported the definition of the WCF service - the client side proxy service contract.
Here's a similar answer I wrote with an example.

MVC and EF Solution Structure - Should you use the Repository Pattern, Service Locator, or both?

Take the scenario where you have the following application:
An MVC 4 Web App
The application talks to an existing database via Entity Framework 5
(with no plans to change to another ORM or database platform).
The application talks to an external SOAP Web Service (the webservice
may change to WCF).
Would you:
Create a generic repository for all the EF entities (e.g.
MyDBRepository), and a repository for the SOAP Web Services calls
(E.g. MyWSRepository). Then create a service class that contains the
business logic uses the two repositories to access data and
implements CRUD methods for all the controller’s needs
(MyApplicationService). Then have the repositories injected into
the service class, and finally the service class injected into the
MVC controller.
Or would you have one service class that handles the db queries and
business logic using the EF generated DBContext and the generated
table entities (e.g. MyDBService), and another service class that
handles the business logic and SOAP web service calls (e.g.
MySOAPWebService). Then have both services injected into the MVC
Controllers.
Or something else.
In the past I’ve worked with option 1. But I’m wondering if that is just adding unnecessary layers of abstraction. If the Entity Framework generates a DBContext, having a service class that uses the DBContext entities directly seems to be less complex.
Having read through several articles and other questions in StackOverflow, it seems like there is a grey line differentiating the Service Locator pattern and Repository Pattern.
Which structure would you use?
I recommend a repository or DAO for each aggregate. make these classes receive the dbContext on the constructor (or unit of work if you prefer).
Then make your service implement the business logic and use the DAOs. The service is responsible for instantiating the DBContext (and a transaction if you require one). Services then call different DAOs with the same context.
For a more strong decoupling I strongly recommend that you make impossible for the service layer to touch the DBContext. Force yourself to go through the DAOs every time.
The service layer should also deal with exceptions. In my applications the service layer only throws 2 types of exception: user and system. On the controllers i use them to tell apart a recoverable error or something else. ( that's why you sometimes see specif errors like "invalid order number" or something else like "An error occurred in the system, try again later")
Btw, never forget to work with disconnected entities. when you call your repositories for add/update always assume the POCO's are disconnected and work with them accordingly.

Design Choice: WCF or Service Stack?

I have three core applications that have their own business functions (networks, active directory and helpdesk). Each are running ASP.NET v2 or v3 and have their own respective databases. However, the application functions have merged a bit so models were recreated in each application and app logic along with it. So now I have some difficult to maintain code. So here is my question:
Is porting my models and repositories over to WCF a reasonable choice for this type of architecture?
Is using a service stack such as serialized json calls a better choice? I'd imagine this would be faster than setting up a central wcf app.
I'm not too familiar with communication between asp.net mvc web apps so please point me in the right direction.
I would recommend developing a service layer per the design pattern described by Fowler. This service layer encapsulates the various domain models and repositories and handles interactions between different domains/models. This will be an assembly and not a WCF or any other type of web service. If you require a WCF web service then it will be a very thin layer which basically has a contract that mimics the service layer and only purpose is to provide a web service interface or API.
There are a couple of ways an MVC application can interact with your service layer. If you are creating view models in your Controllers then it can access the service layer assembly directly. There is added overhead to calling it through a web service that is most likely not necessary in this case. Using this approach the service layer is pretty much your Model in the MVC trio.
The other way to access the service layer is from the Views/client using AJAX for rich clients. In this case you would use MVC to put a REST API on top of your service layer so that you can make AJAX POST's, using something like JQuery, directly to the web service to update and retrieve data for the web page.
Note with this architecture you can use a combination of both approaches. You may access the service layer directly from the Controller to render some initial pages and then use the web service REST interface for AJAX calls during user interaction.

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.

Resources