Encapsulating multiple WCF services into a class library - c#

I have one WCF service with multiple endpoints. Each endpoint has it's own configuration.
My problem is that I'm trying to figure out what will be the best.
1 - Add to my MVC application a service reference to each of the endpoints
2 - Create new DLL that will have the references to each of the endpoints and then add in my MVC application a reference only to this DLL.
I could really use your help to figure if there are any downsides to each of the approaches?
UPDATE
i forgot to mention that i have multiple MVC applications and each one uses only one or two of the WCF services.
to be more accurate, i now have 6 MVC applications and 7 WCF services. each MVC application uses only 2 WCF.
in the future the number of MVC apps and WCF will grow.

I would not use a server reference but just point svcutil to all three at the same time. It will generate one set of proxies and one configuration. It also allows you to share data contracts between the services.

Personally, I always put my web references and service references in a standalone assembly called SharedServices. That way; multiple assemblies can share the same references and datatypes can be shared among assemblies. Attaching a web reference to an assembly could lead to many projects being dependent on that assembly solely for the web service defintions.

You can write a service agent that is responsible for accessing the services, abstracting away this logic for your MVC application. The service agent would also be the place to implement other logic like caching, if you would ever need it. See http://tinyurl.com/cbcepgl, below under 'service agent' for some demo code.

Related

How to config WCF settings from 2 different web applications

I have a WCF project that send emails, log them, and know how to use templating.
There are 2 different web sites that have a service reference to this project, but they need also to provide a From address to the service which I don't want it to be send at each method call, I consider this to be a setting of the service behavior. What is the correct way to do it?
With referencing different project I can use the settings properties section in the web.config, but with WCF this solution won't work.
If I'm understanding correctly you just need common settings between multiple projects, right?
I would go with appsettings and Dependency Injection. It's origin is asp.net core but you could apply the principle anywhere.
For instance:
https://csharp.christiannagel.com/2016/08/16/diwithconfiguration/

How to access a RIA Services WCF WebApp from another WebApp?

I have a silverlight application which accesses its data through RIA Services, from a WCF app in the server. The current structure looks like this:
DataWebServer - A Web application project, which holds the .aspx page that will call the Silverlight components, the .edmx model file and a MyService class, inheriting from LinqToEntitiesDomainService<FortWayneDB>.
Silverlight App - Contains .xaml e .cs files that will generate the .xap binary files, hosted by the WebServer. It access "DatawebServer" project through RIA Services.
It's all working fine, but now I need to create a new application, and since we will going to need it to run on platforms like tablets and smartphones, we decided to build it in HTML5, instead of Silverlight.
How can I make this new WebApp to access the data entities on "DataWebServer" project?
I think of 3 different solutions, but I'd prefer the third one, which exactly my question.
I could place the new WebApp in a folder in the same webprojeect "DataWebServer", but that wouldn't be very organized, I'd rather separate this app from the "DataWebServer".
The second alternative, which I will follow in case I can't succeed with the third, is to create WebMethods in "DataWebServer" to be accessed from my new WebApp.
the third, which I don't know how to do, is to make my new Web App to access the Entities through RIA Services, in the same way the Silverlight Client does. I've searched the Internet, but all articles I've found show how to access RIA Services from the same project. Does anyone know how I can do that?
The first method is the most sensible.
From your details, I assume the DataWebServer is "publicly" accessible; at least as much as your WebApp would be. There is little value in having WebApp data requests go to a different server, DataWebServer, as this introduces an unnecessary delay while one web server calls another. Instead of re-using the HTTP services from DataWebServer, add the WebApp functionality to the DataWebServer and re-use the LinqToEntities context.
If you desperately want the third option, you should consider creating your WebApp in a way that the JavaScript in the app calls the DataWebServer for data from the client's browser. Importantly, this approach avoids WebApp web server calling to DataWebServer for data.

Replace (Entity Framework Connection) to (WebServices) on Services Project

We have the following structure on our project in order to get data.
Acces to Database Using Entity Framework
ProjectName.DAL
Services that call Entity Framework.(UoW)
ProjectName.Service
Our Actions inside Controllers call Services and return data needed.
ProjectName.Web
The Question:
Our services take info directly with Entity Framework, What are the advantages and disadvantages about creating WebServices in order to replace the connection with EF? "In that case only WebServices will have access to Entity Framework,"
ProjectName.DAL
ProjectName.WebServices
ProjectName.Service
ProjectName.Web
The main advantage is that you would have a more decoupled design.
By exposing your DAL through web services you "disconnect" it from your frontend. For example, a mobile app, a web app and a WPF desktop app could all access your DAL through the same web services. So you can reuse your DAL accross different apps which can save you a lot of development time. Have a look at ServiceStack and advantages of its web services.
Disadvantages? Having to do some additional development work and testing. If your app is a simple and will not be used in different environments it may be overkill to use web services.
Disadvantages:
Web services tend to consume more resources from your server than just a plain CLR (aka dll) layer in your project.
whatever web service you plan to use (legacy web services, service stack, wcf, Web API, etc) you'll find that all of them have to use a process to serialize the data and it could be the case that you'll need to do the inverse process in your front end application.
you have to design your ws very carefully because you have to think how you're going to expose those services and the level of encapsulation/abstraction you will have to put in place, a bad design in a web service layer definetely will be a headache for you during development and production.
Security: In most cases you will have to validate every input in those web services as well
Advantages
well that's very relative to call an advantage, it depends more on what are your app requirements, some questions you need to answer are like the following:
Do I need to share data with other apps (mobile, desktop, other web
apps)?
Do I need to expose some functionalities to other business (third
parties)?
Recomendation
If you plan to do a CRUD application I'll recomend to go with REST definetely is the best option due to it's architecture (POST,DELETE,GET,ETC).
if you don't need you a web service right now, you can try to develop your service layer kind of like a service implementation in service stack but try to remain as POCO as possible and if for some reason you'll need a web service you can try to refector the service layer intead to have another level of indirection in the middle.
just my two cents...

Add WCF service to website project

I have an asp.net Website that has access to database and has functions which I want to allow 3rd party users to use.
Is it possible to add WCF project/ WCF service to my solution so i could let 3rd party member having access to my methods?
We tried myWebsite->Add New Item-> Wcf service/wcf data service but that doesn't seem to work.
Any help would be great.
It's not working because you are trying to add a reference to an existing service for consuming it. You want the exact opposite.
For this, you will have to create a separete project of type WCF Service in your solution.
More info on creating WCF Services can be found on MSDN.
Keep in mind that if you want to expose certain features through the service, you will have to factor the functionally out of the website to another project that both the WCF Service and the website can consume.
You should be able to add a new WCF service project from the solution root in Solution Explorer...
Right-Click >> Add >> New Project
It's not clear from your question what 'doesn't work' though.
Your newly added project will need to reference the existing project that contains the methods that you want to access. You should perhaps consider if your current design is appropriate - ensure that you have separated out your presentation code (this should be your website project) from the common business functions that you want to share (I would have this as a separate class library project in the solution). Your WCF project can then reference the common 'business logic' project.
To reference your 'business logic' project from the WCF project...
Right-Click (on WCF project) >> Add Reference
Not sure what "doesn't work", but MSDN providers a walkthrough for adding a WCF service to a website here:
How to: Host a WCF Service in IIS
This has the step-by-step of creating a WCF (both markup and code) and adding the relevant web.config entries by hand rather than using the "Add Service" dialog.
If you create a separate project in your solution to run your services, you will need to reference your existing website project using the Add Reference option on the new service project. This will allow you to use the classes and functions defined in the existing project inside your new service project.

Web API in MVC solution in separate project

I am creating a new MVC4 project, and research has lead me to believe that communicating from javascript to the server side is better achieved now through web API framework rather than controller actions. Is my understanding correct on this?
I am presuming that I can share all my attributes etc between web API and MVC controllers so on the face it, it does not seem a massive change for me.
When I am setting up applications, I like to split components out in to projects. My plan was to have a MVC project and a web API project. But I have ran in to issues. For example I have ended up with 2 apps as such, separate routing set up etc etc.
So my question is, in a MVC application should the web API framework sit within the same project, or should the web API be separated into a project of its own and work around the issues?
Unfortunately you are wrong about that - I am presuming that I can share all my attributes etc between web api and mvc controllers so on the face it, it does not seem a massive change for me.
Many of the concepts used by Web API and MVC, even though similar at first glance, are actually not compatible. For example, Web API attributes are System.Web.Http.Filters.Filter and MVC attributes are System.Web.Mvc.Filter - and they are not interchangeable.
Same applies to many other concepts - model binding (completely different mechanisms), routes (Web API uses HTTPRoutes not Routes, even though they both operate on the same underlying RouteTable), dependency resolver (not compatible) and more - even though similar on the surface, are very different in practice. Moreover, Web API does not have a concept of areas.
Ultimately, if all you are trying to do achieve is to have a "new, trendy" way of serving up JSON content - think twice before going down that path. I certainly wouldn't recommend refactoring any existing code unless you are really looking into embracing HTTP and building your app in a RESTful way.
It all really depends on what you are building. If you are starting a new project, and all you need is to serve up some JSON to facilitate your web app - provided you willing to live with some potentially duplicate code (like the stuff I mentioned above), Web API could easily be hosted within the same project as ASP.NET MVC.
I would only separate Web API into a separate project if you are going to build a proper API for your online service - perhaps to be consumed by external customers, or by various devices - such as fueling your mobile apps.
IMO, security and deployment should drive your decision. E.g., if your MVC app uses Forms authentication but you're interested in using Basic authentication (with SSL) for your API, separate projects are going to make your life easier. If you want to host yout site at www.example.com but host your API as api.example.com (vs. www.example.com/api), separate projects will make your life easier. If you separate your projects and subdomain them accordingly and you intend to leverage your own API from your MVC app, you will have to figure out how to deal with the Same Origin Policy issue for client-side calls to your API. Common solutions to this are to leverage jsonp or CORS (preferably if you can).
Update (3/26/2013): Official CORS support is coming: http://aspnetwebstack.codeplex.com/wikipage?title=CORS%20support%20for%20ASP.NET%20Web%20API
After some degree of experience (creating API for apps and for mvc). I mostly do both.
I create a separate project for api calls that come from other clients or other devices (Android/IOS apps). One of the reasons is because the authentication is different, it is token based (to keep it stateless). I do not want to mix this within my MVC application.
For my javascript/jquery api calls to my mvc application, I like to keep things simple so I include a web api inside my MVC application. I do not intend to have token based authentication with my javascript api calls, because hey, it's in the same application. I can just use [authorize] attribute on a API endpoint, when a user is not logged in, he will not get the data.
Furthermore, when dealing with shopping carts and you want to store a users shopping cart in a session (while not logged in), you need to have this in your API as well if you add/delete products via your javascript code. This will make your API stateful for sure, but will also reduce the complexity in your MVC-API.
Steven from SimpleInjector (IoC framework) advises two separate projects: What is the difference between DependencyResolver.SetResolver and HttpConfiguration.DependencyResolver in WebAPI
I have recently done almost the same thing: I started with a new MVC 4 web application project choosing the Web API template in VS2012.
This will create a Web API hosted in the same application as MVC.
I wanted to move the ApiControllers into a separate class library project. This was fairly easy but the solution was a bit hidden.
In AssemblyInfo.cs of the MVC 4 project add similar line of code
[assembly: PreApplicationStartMethod(typeof(LibraryRegistrator), "Register")]
Now you need the class LibraryRegistrator (feel free to name it whatever)
public class LibraryRegistrator
{
public static void Register()
{
BuildManager.AddReferencedAssembly(Assembly.LoadFrom(HostingEnvironment.MapPath("~/bin/yourown.dll")));
}
}
In the MVC 4 project also add reference to the Api library.
Now you can add Api controllers to your own separate class library (yourown.dll).
Even if your project is so complex as to warrant two "front ends" then I would still only consider splitting out webapi into a separate project as a last resort. You will have deployment headaches and it would be difficult for a newbie to understand the structure of your solution. Not to mention routing issues.
I would aim to keep the system.web namespace isolated in the one "presentation layer". Despite the webapi not being presentational it is still part of the interface of your application. As long as you keep the logic in your domain and not your controllers you should not run into too many problems. Also, don't forget to make use of Areas.
In addition to setup the separate DLL for the Web.Api.
Just a Suggestion:
Create the Project
Nugget WebActivatorEx
Create a a class Method to be called upon app_start
[assembly: WebActivatorEx.PostApplicationStartMethod(typeof(API.AppWebActivator),"Start")]
[assembly:WebActivatorEx.ApplicationShutdownMethod(typeof(API.AppWebActivator), "Shutdown")]
Register a web.api routes inside the Start Method
public static void Start() {
GlobalConfiguration.Configure(WebApiConfig.Register);
}
Reference the Project to the Web Project. to activate the Start Method.
Hope this helps.
I tried to split the API controllers into a new project. All I've done is to create a new library project, moved the controllers inside folder named API.
Then added the reference of the library project to the MVC project.
The webAPI configuration is left in the MVC project itself. It works fine.

Categories