Using Virtual Methods to Override Behavior

Applies to: Windows Communication Foundation

Published: June 2011

Author: Alex Culp

Referenced Image

This topic contains the following sections.

  • The Unity Interception Container
  • Conclusion
  • Additional Resources

The Unity Interception Container

The DependencyInjectionServiceHostFactory class allows you to inject dependencies directly into your service, but it does not allow you to inject any behaviors, such as exception management, or validation, either before or after your service operation executes. This is because you cannot specify an interface in your SVC file. If you try the following error appears.

Exception When Specifying an Interface in a SVC File

Referenced Image

Fortunately, you have another option. The Unity Interception container extension can not only inject behavior into interfaces, but it can also override the behavior of virtual methods to inject new behavior. The Interception container extension's VirtualMethodIntercepter class can create a new derived class at run time, inject your behavior, and then call the target class. The ability to inject new behavior is necessary in order to get all the benefits of a custom ServiceHostFactory. For more information about the VirtualMethodIntercepter class, see https://msdn.microsoft.com/en-us/library/microsoft.practices.unity.interceptionextension.virtualmethodinterceptor.aspx.

You can register a VirtualMethodIntercepter object either with configuration, or you can register it in code from within the custom ServiceHostFactory. For information about how to configure a Unity container for Interception, see "Configuring a Container for Interception" at https://msdn.microsoft.com/en-us/library/ff660911(v=pandp.20).aspx.

Note

To use the VirtualMethodInterceptor class, all of your service methods must be virtual, and your service must be public. The Interception container extension validates that this is true. Methods must be virtual so that they can be overridden.

Conclusion

The techniques that are discussed in this article enable you to use DI in your WCF services. The use of DI will help you to design more testable services. DI also gives you the ability to inject custom behaviors such as exception management, performance counters, and logging. In addition, if you use an instance provider in combination with a service host factory, you will eliminate an extra abstraction layer, need only a single constructor, and have a single point where you can register all dependencies, without having to use configuration files.

Additional Resources

For more information, see the following resources:

Previous article: Using Instance Provider and ServiceHostFactory to Construct the Service

Continue on to the next article: Exception Management in WCF