Landon
Landon

Reputation: 561

Dependency Injection & Web Services (Specifically WCF)

I've been doing a lot of research on dependency injection and service locators (and comparisons between the two). I can definitely see the benefits of dependency injection especially with regards to test driven development. While we don't currently practice test driven development it's a practice I'd like to start implementing on my development team. It is a requirement, however, that nearly all of our database calls must go through a web service. We are more commonly using WCF services than traditional web services for new development projects. What I'm struggling to understand is the idea of injecting the Dataprovider dependency into our webservice.

It doesn't quite make sense to me that the client should have to tell the service where to pull data from. Is it "acceptable" to just have the WCF service be tightly coupled with the Dataprovider? This seems to break the fundamental idea of unit testing without external dependencies. I'd appreciate any feed back on the matter.

Upvotes: 0

Views: 1146

Answers (2)

jevakallio
jevakallio

Reputation: 35890

Depending on the complexity of your scenario, you may want to build a decoupling layer to your WCF service application, and this is where using Inversion of Control can make sense.

The client obviously shouldn't know, much less tell the service, what data provider to use. It is the job of your WCF service to decide that. You can either use a service locator inside the WCF class constructor, or you can inject the required service using an IInstanceProvider or ServiceHostFactory.

From there it's up to you to decide what services your WCF application uses.

One common solution is to abstract the data persistance using the Repository pattern, which makes sense especially if your WCF service contains any significant business logic. In this type of scenario you would build repository classes which perform all data provider -specific logic. These classes can then me mocked or stubbed to enable unit testing the services.

In other cases, especially when your WCF services expose CRUD operations with little or no business logic, I find building an extra layer between the service endpoints and the database is pointless. Ultimately, at some point down the line some part of your program needs to know about the database. Using DI/SL/IoC shouldn't be a goal unto its own.

Upvotes: 1

Pedro
Pedro

Reputation: 382

The client would not dictate where the data comes from. All the dependency injection would occur on the server.

Upvotes: 0

Related Questions