Consuming WCF In .Net

Recently I’ve been working on a system that consumes several WCF Endpoints that share types and are part of the same larger system. To this end I use an abstracted service factory to provide a wrapper that lets me call against my service interface and ensure that it is cleaned up correctly, by wrapping calls to client in what I call a proxy wrapper. I don’t call nakedly against a wcf client.

I used dependency injection so where I need to make my WCF calls I inject a service factory, and that provides what I call proxy wrappers. Code to run against the client is passed as lambda expressions and cleanup code is kept in the proxy wrapper. Looks like this:

public void DoSomething(int id)
{
    IProxyWrapper<IService> proxyWrapper = ServiceFactory.GetService<IService>();
    Data data = null;
    proxyWrapper.ExecuteAndClose(x => data = x.DoSomething(id));

    return ResponseProcessor.CreateResponse(data, context);
}

I thought the above was a good idea because the try/catch around the wcf client, and the wcf client’s lifetime were no longer a problem of the consumer of the service, the proxy wrapper and service factory would worry about it.

From a testing perspective it was a little weird because I had to program a service factory mock to return a mock proxy wrapper that would run code against a mock client. It is not hard and allows for unit testing, but it is always difficult to explain to someone else.

Recently I ran into a pattern where instead of using a WCF client at all, a client class is created that wraps the WCF client in a way that the consumer would not know or care if the functionality is presented as a WCF client or not. In this pattern the client class handles all details of WCF, or whatever mechanism is used to communicate, and the caller simply references and calls against the client class directly. The same code above becomes:

public void DoSomething(int id)
{
  IServiceClient serviceClient = ServiceFactory.GetService<IServiceClient>();
    Data data = null;

    data = serviceClient .DeleteCheckCall(id);

    return ResponseProcessor.CreateResponse(data, context);
}

The above looks a lot more normal to someone not indoctrinated into the intricacies of WCF. It is also easier to test since I just have to have my service factory return a mock of the client. Also if I have to pass data over the service that is hard to serialize I can hide that problem from my consumer by allowing them to pass data regardless of whether it’s hard to serialize and then handling serialization behind the scenes in the client wrapping class.

The only downside is then when I create a service I have to create a client interface and class to wrap calls to that service. Also, this client is only going to be consumable by code that the client is shared with. The same goes for the proxy wrapper I suppose.

All in all I think I like the client class that hides all WCF details from the consumer. Makes it easier if need to change communication mechanism since nothing that is done is specifically to accommodate WCF, as in the proxy wrapper where functionality is passed as lambda’s to all it to be encased in error handling code.

I figured there was a better way then what I was doing and I think I was right.

When Static Methods Apply

In my current project we are using Dependency injection and are trying to depend on abstractions instead of implementations as much as possible. Someone recently added a static method call to resolve mappings of properties between a DTO and an Entity. My first reaction to this was that it should not be static. When asked why, I stated that if the mapping was static then wherever it is called I have to know what it is doing in order to unit test code that contains calls to it. When I heard myself say this it made me think, if it does not impact my ability to unit test code that calls it maybe it’s ok? I still think it is better to not directly couple the mapping implementation to callers, but if it does not impede the ability to unit test the callers then really it is more of standards question. So, in light of that if your standard isn’t to inject all dependencies and a dependency does not cause testing difficulty then I suppose it is ok.

That said I think there is value in sticking to standards so that readers of your code and other developers have a reasonable expectation of what they’ll find in a given circumstance. That is debatable, however.

EF Code First Needs Master Database Access

At my current client they are beginning to move towards EF code first for data access. This is a large improvement over their home grown system. I did have one hiccup initially. The connection I am using for my EF DbContext is an already existing connection that does not have credential information on it. Apparently when calling through the DbContext for the first time EF queries the master database to make sure the database you want actually exists. Not sure why they chose to do this, but OK. Problem arises in that my connection does not have access to the master database, only to the one I want to actually connect to, that is already connected to ironically enough.

After googling around some I found that you can tell EF to skip the check to master if you make the below call before your context is ever called:

 Database.SetInitializer<MyContext>(null);

Apparently the above line tells EF to assume you are smart enough to call a database that does exist, and if it does not you can just error, without checking the master db first.

I just put in the constructor of the context so it is not forgotten:

  public class MyContext : DbContext, IMyContext
    {
        public MyContext()
            : base(ApplicationManager.GetConnection, true)

        {
            Database.SetInitializer<MyContext>(null);
        }

If you’ve noticed the static call to get the connection, just ignore it, it’s a whole other story.

Unity and RhinoMocks, I Like

On my current project we have been using Unity as a Dependency Injection Container. Previously to this project I had always created constructor overloads, so any dependencies could be injected for testing or replacement. Typically what I might have done would have looked something like this:

 public class MessageReceivingService : IMessageReceivingService
    {
        internal IMessageProcessor _MessageProcessor;
        internal IMessageRepository _MessageRepository;


        public MessageReceivingService()
            : this(new MessageProcessor(), new MessageRepository())
        { }

        public MessageReceivingService(IMessageProcessor messageProcessor, IMessageRepository messageRepository)
        {
            this._MessageProcessor = messageProcessor;
            this._MessageRepository = messageRepository;
        }

    }

The above allowed me to inject and change my dependencies. In a test I’d create mock objects for the dependent objects and call the constructor that takes the dependencies as parameters. The constructor with no parameters creates the default dependencies. A typical unit test looked like the below:

        private IMessageProcessor _MessageProcessorMock;
        private IMessageRepository _MessageRepositoryrMock;


        [TestInitialize]
        public void Setup()
        {
            this._MessageProcessorMock = MockRepository.GenerateMock<IMessageProcessor>();
            this._MessageRepositoryrMock = MockRepository.GenerateStub<IMessageRepository>();
        }


        [TestMethod]
        public void Checking_That_Some_Behavior_Works_Test()
        {
            //--Arrange
            MessageReceivingService serviceToTest =
                     new MessageReceivingService(this._MessageProcessorMock, this._MessageRepositoryrMock);

            Message testMessage = new Message();

            //--Act
            serviceToTest.ProcessMessages(testMessage);
            

            //--ASSERT
            this._MessageProcessorMock.AssertWasCalled(imd => imd.SaveMessage(Arg<PostOffice.Data.Message>.Is.Same(testMessage)));

        }

This allowed me to unit test and inject mocks. I was really only trying to allow myself the ability to inject mocks in unit testing. If it ever came up I could use the constructor overloads to override the default dependencies, but I was not that worried, that happened very infrequently.

What I did realize, and did not like, was that every time a dependency was added, I had to go change all my constructor calls in my unit test to allow for the new dependency. That was a pain, but not painful enough to make me change anything apparently.

Now that I started using Unity for DI The above class becomes this:

public class MessageReceivingService : IMessageReceivingService
    {
        internal IMessageProcessor _MessageProcessor;
        internal IMessageRepository _MessageRepository;
        internal IUnityContainer _Container;


        public MessageReceivingService()
            : this(new ConfiguredUnityContainer())
        { }

        public MessageReceivingService(IUnityContainer container)
        {
            this._Container = container;
            this._MessageProcessor = this._Container.Resolve<IMessageProcessor>();
            this._MessageRepository = this._Container.Resolve<IMessageRepository>();
        }

    }

ConfiguredUnityContainer is just a class extending UnityContainer that loads types from a default container in configuration. The above allows for an existing container to be passed in, or for a new one to be created and used. I wasn’t crazy about having dependencies to unity in my constructor, but I consoled myself since the dependencies were on the IUnityContainer interface and a class I had extended from UnityContainer.

It was in my unit tests that I realized how this was really going to help me. My unit test above now changed to this:


	private IMessageProcessor _MessageProcessorMock;
	private IMessageRepository _MessageRepositoryrMock;
	 
	[TestInitialize]
	public void Setup()
	{
	    this._MessageProcessorMock = MockRepository.GenerateMock<IMessageProcessor>();
	    this._MessageRepositoryrMock = MockRepository.GenerateStub<IMessageRepository>();
	}

[TestMethod]
        public void Checking_That_Some_Behavior_Works_Test()
        {
            //--Arrange
            IUnityContainer container = new UnityContainer();

            container.RegisterInstance<IMessageProcessor>(this._MessageProcessorMock);
            container.RegisterInstance<IMessageRepository>(this._MessageRepositoryrMock);

            MessageReceivingService serviceToTest =
                            new MessageReceivingService(container);

            Message testMessage = new Message();

            //--Act
            serviceToTest.ProcessMessages(testMessage);
            

            //--ASSERT
            this._MessageProcessorMock.AssertWasCalled(imd => imd.SaveMessage(Arg<PostOffice.Data.Message>.Is.Same(testMessage)));

        }

The first thing I realized was that I would no longer have to change my constructor if I added a dependency! Now my only constructor overload takes an IUnityContainer. I just set my dependencies in the test code, setting my mock objects as the served up dependencies. No matter how many dependencies I add or remove my constructors will never change.

As an added bonus, I can now replace dependencies on the fly. If I deliver a container that is mapped in a config file, I only have to change the config file to change served up dependencies. I was not really that worried about changing dependencies on the fly since it seemed to happen so rarely, but I certainly do not mind that it is now easy to do should the need arise.

I probably should have realized there was more value to a DI container then just serving up mocks in tests, but even in this context the DI container made my life easier. I have to say I really like the combination of Unity and RhinoMocks. I’m kicking myself for not looking into this myself before Unity was forced on me on a project!

Someone Recently Asked What Design Patterns I Used, Here’s What I Said.

There are a few design patters I use frequently, mainly because in business software the problems they are geared at solving come up often. The first is the Command pattern. This pattern in demonstrably useful in UI operations as it supports a generic means for undo and redo operations. When UI operations are implemented as atomic Command classes their undo redo operations are explicitly defined in a concrete object, and are generically invoked from the stack managing the executed commands as base commands. I have also come to find that the Command Pattern is very useful in pure business logic as well. In environments where distributed transactions are involved the Command pattern allows the definition of atomic transactions to be defined as a command in the business logic layer. The benefit of this structure is that each atomic Command can be chained and composite transaction behavior can be defined in the base Command class instead of by each operation itself.

There are two other patterns I use frequently to make code less coupled and more testable. The first, the Factory Pattern, was much more helpful before the wide acceptance of dependency injection frameworks. The Factory Pattern allows me to abstract the creation of classes from their consumers. This allows the consumed class to be an abstraction, an interface, and allows the management of its creation to be removed as a concern from the consumer. From a testing perspective this allows the injection of mock objects in situations where a consumer of an object is being unit tested and the consumed object has an outside dependency, such as connecting to a database or making a network call. The Factory Pattern also keeps the consumer from being directly coupled to the object it’s consuming. This lesser coupling makes it that much easier to manage changes to the consumed object. If changes to the consumed object do not change the interface the consumer is using, then changes to the consumed object have no effect on the consumer at all.

I use the Singleton Pattern frequently to apply abstraction to objects that do not need to keep state. Static classes cannot implement interfaces, which makes it difficult to mock them when testing their consumers. Singletons allow for a method of applying an interface to what otherwise would be a static class. Using a Singleton instead of a just creating a separate instance for each call to a class allows for more efficient memory management since only one instance to manage, and the interface allows the Singleton to be mocked when and if necessary.

Lately I have used the Mediator Pattern. This pattern became useful in the UI work I have done in the context of event handling. I implemented a Mediator Pattern to create an event aggregator so event handlers and throwers would register and listen and throw events to the event aggregator, instead of directly to each other. This assisted in minimizing memory leaks due to improper releasing of event references , and also decreased coupling of classes needed for direct event relationships.