WCF + TDD : adding service references to your test projects: Bad? - asp.net-mvc

I'm starting to TDD and I want to know if it is a bad practice to add a service reference to test my project or if I just mock a fake service on my tests that depends of the WCF service.

Yes it is a bad practice to add service references to a unit testing project. You could use the generated service contract interface to mock the real WCF service behavior in the test.

Having a service ref is possible a bad way to go, you could consider implementing the Gateway Pattern, e.g. IMyFooServiceGateway as an additional abstraction layer. This way you might be able to make the app more loosely coupled and gain some additional testability (in you test project you'd reference the segregated assembly containing IMyFooServiceGateway and either hand-create a mock that implements IMyFooServiceGateway or use a mock framework like Rhino Mocks to create one for you.

Rather than using a service reference you could mock out a ChannelFactory using your service contract.

If the project which is the target for the tests has a service reference, you should not have to add an additional service reference to the test project.
When a service reference is added to a project, usually the code generated for it contains a publicly accessible interface to the service. The test project therefore only need reference the target project in order to see this interface, which can in turn be dropped into your mocking library of choice or mocked out manually.
It's worth noting though that the interface generated doesn't necessarily follow the typical "IFoo" naming convention for interfaces so it isn't immediately obvious.

Related

ASP.NET MVC dependency injection outside the controller with Unity

I am building an ASP.NET MVC 5 application using the repository and service layer design patterns. I have used unity to inject my services into my controllers.
This works nicely and until now I have not had a need to consider instantiating any objects requiring injection of interfaces outside my controllers. However I have a need for this when configuring my application startup to setup some users in the database.
For this I wanted to user my UsersService that I've built. And it occurred to me as the application grows there will surely be other occasions when I'll want to do the same, such as calling a service from within another service.
I see that I can instantiate a Unity container and call resolve on it to get my new instance of a service:
IProductService productService = container.Resolve<IProductService>();
However this kinda smells to me, having the container leaked all over my application seems like an anti pattern. So is there a better way to do this?
Unity and other dependency injection containers automatically do this. When you inject a service into a controller, it will automatically resolve the entire dependency graph of that service. Not only can you resolve dependencies of the service and its dependencies, you should inject dependencies into the service that needs them instead of the controller.
Any class (including the controller) that has more than a handful of dependencies is a code smell that you are violating the Single Responsibility Principle, and you most likely should refactor to aggregate services.
And yes, injecting the container to any point outside of the composition root is an anti-pattern called a service locator.
As for injecting services outside of the controller, it is important to distinguish between injectables and runtime data. For example, some try to inject services into DTO objects, attributes, static classes/extension methods, and other places where it is anti-pattern for services to be injected. For these situations, it is important to properly assess the situation and refactor toward a DI-friendly solution - favoring constructor injection over other alternatives and considering a service locator as a last resort. For example, if you are trying to make an extension method with a dependent service, most likely you have some functionality that itself should be a non-static service, DTOs should never be created from a DI container, and you may have to make use of more than one extension point in MVC where you inject the container within the composition root of the application, which does not constitute a service locator.
Is it worth it? Usually. What is gained? You gain the ability to change the application much more quickly than if you have a tightly-coupled application in ways that the designer of the application may not have even anticipated. So the extra cost of ensuring the application is loosely-coupled is usually more than recouped in ongoing maintenance of the project. As a side benefit, you gain the ability to easily unit-test each component independent of the others.

Where should I configure my DI container for domain infrastructure services in DDD?

I am trying to figure our where the code for configuring my dependency injection container for my domain repository services lives.
My initial thought was to let the client configure all services, but then the client needs to be aware of the repository service, which I don't want to expose in the client.
I was thinking that each layer could configure its own service dependencies via an exposed configuration method or class?
My initial thought was to let the client configure all services, but
then the client needs to be aware of the repository service, which I
don't want to expose in the client.
What I tend to do is still follow the Composition Root pattern, where my web project would be the first place where the IoC wiring-up would start (i.e. the usual sort of 3rd party library that would hook itself into the controller factory). But I then configure the rest of my IoC bindings by referencing an IoC module (in my case I usually use Ninject, so I reference a NinjectModule from my web project). But I put this NinjectModule in a separate infrastructure project.
I can then reference this IoC infrastructure project from my web project and the IoC project can reference every other project in the solution.
This way I don't have to create project references in my web project to things I might not want my web project to access, like my repository layer.
The answer has already been given in comments, I'm just wrapping it up in a proper answer here.
Unless you use a special-purpose architecture like a plug-in architecture, you should always configure the DI container at a single place, as near to the application entry point as possible. This is called the composition root.
It doesn't matter if the configured type is a repository, factory, domain service or application service. All DI configuration should go in one place.
See this blog post for a good introduction on the details of composition roots.

ZF2 Injecting a service to all the services by default

I have an authentication_service, which is required in all the services throughout the application. So, I don't want to inject this service every time (DRY). Is there a way, I can have this common service accessible from all the modules, with injecting via factory?
Thanks!!
You can use service initializers, great article with examples and more important with explained consequences:
http://www.masterzendframework.com/zend-framework/easy-setter-injection-in-zend-framework-2
I suggest you create a base service which defines all the common service requirements, such as your $authService property and the constructor that sets it. Then have your services extend that. Avoid reimplementing the constructor and property in every service to stay DRY, but injecting it via every service's factory is expected.

When to allow Services to access the IoC Controller?

What are the scenarios in which it's OK to allow services created via IoC to have access back to the IoC controller to access other services? It seems to me that the short answer is never, but are there situations in which it's OK or even in which it makes sense?
I think the answer is 'never', since it sounds like what you describe is service locator, which is an anti pattern
There's a rather well written article about this from Martin Fowler:
http://martinfowler.com/articles/injection.html#UsingAServiceLocator
A lot of this depends on the nature of the user of the service. If you
are building an application with various classes that use a service,
then a dependency from the application classes to the locator isn't a
big deal. In my example of giving a Movie Lister to my friends, then
using a service locator works quite well. All they need to do is to
configure the locator to hook in the right service implementations,
either through some configuration code or through a configuration
file. In this kind of scenario I don't see the injector's inversion as
providing anything compelling.

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