Skip to main content

Posts

Showing posts from August, 2013

Proper initialize/dispose with WCF and MEF

Initialization and disposing of services in a WCF application is a bit of a hassle to control when running on an IIS instance, since the application starts and stops every now and then based on server requests. It doesnt make it easier when using an IOC, as in our case MEF. To have total control of the startup and shutdown events we began with adding a service factory to all our WCF services. <%@ ServiceHost Language="C#" Debug="true" Service="WcfService" Factory="CustomServiceHostFactory" %> When ever the application gets woke up by a request to any of the services, the service factory will be used to instantiate the service. This means we can add any logic to these methods to have full control of the WCF application initialization. Here is what a service factory class could look like. (Composition is a static class containing a reference to the MEF container) public class CustomServiceHostFactory : ServiceHostFactory { priva

Custom DataAnnotation validation on multiple properties

There are a few cases where you want to be able to validate a property value based on the value of another property. As always there are a bunch of different solutions to this problem, but the cleanest way of doing so is to create a custom DataAnnotaion validation attribute. It is as easy as creating a class derived from ValidationAttribute and overriding the IsValid-method, but instead of the usual IsValid(object value) we will be overriding the IsValid(object value, ValidationContext validationContext) method. The ValidationContext contains information about the current object beeing validated and makes it possible to get the values of related properties. By including the related properties and values in our validation class constructor. All in all, it could look like this, even though the validation logic does not really make sense in a real world context it explains the idea pretty good. [AttributeUsage(AttributeTargets.Property)] public class CustomValidationAttribute : Val