Windows Support Number

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Monday, 8 October 2012

Using CompositeDisposable in base classes

Posted on 09:21 by Unknown
To help make an object eligible for collection by the GC (garbage collector) one would implement the IDisposable interface. Executing the dispose methods on muliple implmentations at the correct same time is often done using a custom DisposeWith extension method:

   1:  public static class DisposableExtensions
   2:  {
   3:      public static T DisposeWith<T>(this T disposable, CompositeDisposable disposables) where T : IDisposable
   4:      {
   5:          disposables.Add(disposable);
   6:   
   7:          return disposable;
   8:      }
   9:  }

Typically used as follows - explicitly creating a CompositeDisposable instance and then disposing the child view model with the instance:
Firstly can I get away without having to explicitly create an instance?

Also can I get to a point where I can just do something like this:
Inheritance seems the obvious choice but as you might already know, all the disposable types in the System.Reactive.Disposables namespace are sealed by design.

So inheriting directly from CompositeDisposable is a none starter, the next option would to create an intermediate class, @leeoades has a post showing the type of implementation we're using at the moment.

   1:  public interface IDisposableObject: IDisposable
   2:  {
   3:      void AddDisposable(IDisposable disposableObject);
   4:  }
   5:   
   6:  public class DisposableObject : IDisposableObject
   7:  {
   8:      CompositeDisposable _compositeDisposable = new CompositeDisposable();
   9:   
  10:      public void AddDisposable(IDisposable disposableObject)
  11:      {
  12:          _compositeDisposable.Add(disposableObject);
  13:      }
  14:   
  15:      public virtual void Dispose()
  16:      {
  17:          _compositeDisposable.Dispose();
  18:      }
  19:  }

This works well and does the job, but it does introduce another class into the inheritance hierarchy,e.g:

   1:  public abstract class ViewModel :  DisposableObject
   2:  {
   3:  }
   4:   
   5:  public class ParentViewModel : ViewModel
   6:  {
   7:  }

I always want to reduce the levels of inheritance as much as possible, especially when you're working on a framework that's going to be used by a wide variety of developers - keeping inheritance to a minimum helps new devs grok your code base quicker. It also introduces another line into the intellisense when using any derived classes, again this can be confusing when you're not au fait with the classes.
The other downside is having to change the DisposeWith extension method to have an instance of DisposableObject as the second parameter:

   1:  public static class DisposableExtensions
   2:  {
   3:      public static T DisposeWith<T>(this T disposable, IDisposableObject disposableObject) where T : IDisposable
   4:      {
   5:          disposableObject.AddDisposable(disposable);
   6:   
   7:          return disposable;
   8:      }
   9:  }

Is there away I can achieve the same functionality without introducing the DisposableObject class and not expose class methods that aren't relevant?

Yes - use a conversion operator, specifically use an implicit operator to convert from the source type to the destination type without having to specify the type using a dynamic cast. Below is taken from the MSDN example:
So now I'm able to remove the need for the DisposableObject class and prevent the need for any extra methods in my base class ViewModel. You'll notice I've also implemented the ICancelable interface from the  system.Reactive.Disposables namepsace, this exposes an IsDisposed method:

   1:  public abstract class ViewModel : ICancelable
   2:  {
   3:      private CompositeDisposable _disposable;
   4:   
   5:      protected ViewModel()
   6:      {
   7:          _disposable = new CompositeDisposable();
   8:      }
   9:   
  10:      public bool IsDisposed { get; private set; }
  11:   
  12:      public void Dispose()
  13:      {
  14:          if (!IsDisposed)
  15:          {
  16:              IsDisposed = true;
  17:   
  18:              _disposable.Dispose();
  19:              _disposable = null;
  20:          }
  21:      }
  22:   
  23:      public static implicit operator CompositeDisposable(ViewModel viewModel) 
  24:      {
  25:          return viewModel._disposable;
  26:      }
  27:  }

The parent & child view models haven't changed in declaration:

   1:  public class ParentViewModel : ViewModel
   2:  {
   3:  }
   4:   
   5:  public class ChildViewModel : ViewModel
   6:  {
   7:  }

 The intellisense has subtly changed, no longer exposing method declared on the DisposableObject class:
Testing produces the expected output - all view models disposed...

Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest
Posted in C#, Developement, Reactive | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Unit testing Rx methods Timeout & Retry with moq
    Earlier this week I was trying to unit test an asynchronous service (Foo) which used another asynchronous service (Bar) internally and ran i...
  • Be careful of the culture when using Bing Maps REST API
    When developing the Bing Maps Wrapper service for the WP7Contrib we weren't aware of the importance of the instance of the CultureInfo ...
  • WP7Contrib: Bing Maps REST Services Wrapper - Deep Dive
    Following on from Rich's post introducing the Bing Maps Service in the WP7Contrib I'm going to explain in more detail how we built ...
  • MVVM anti-pattern: View code behind with no implementation
    I've seen rather a lot of this anti-pattern recently, to be explicit about what I mean, lets define this in terms of a WPF user control....
  • Implementing a message box using a visual overlay in MVVM
    I've blogged about implementing a busy indicator before, this post is an extension of this pattern to implement a message box - this is...
  • MVVM anti-pattern: Injecting the IoC container into a View Model
    This is another anti-pattern I've seen a lot recently, the dynamic use of the IoC container inside a view model to resolve child view mo...
  • Using IoC nested lifetime scopes with View Models in MVVM
    A common pattern you see when developing web services is the use of the Unit of Work applied to the HTTP request - anything that happens dur...
  • WP7Contrib: URL shortening in a WP7 app
    I needed the ability to shorten a URL for a WP7 app the other day so I could share a URL via the ShareLinkTask, more info about this task ca...
  • MVVM anti-pattern: explicitly using data context in View code behind
    I believe explicitly using the data context in the code behind of the view (custom, user control etc) in any MVVM application is an anti-pat...
  • WP7Contrib: Thread safe ObservableCollection<T>
    Continuing with the introduction of WP7Contrib concepts, patterns & services from my previous post I thought I would explain why we hav...

Categories

  • .Net
  • .Net 4.5
  • Abstractions
  • Advertising
  • Agile
  • Agile Courage
  • AOP
  • Async
  • automated testing
  • Azure
  • Azure IIS RESTful development
  • BDD
  • Bing Maps
  • Bounded Context
  • C#
  • C# 5.0
  • Caching
  • Chocolatey
  • CLoud
  • CodePlex
  • Coding
  • Coding Building CI Testing
  • Coding C#
  • coding C# IoC StructureMap
  • Coding Functional-Programming
  • Coding REST Knowledge
  • Coding Services
  • Coding TDD Refactoring Agile
  • Command
  • continuous testing
  • coupling
  • CultureInfo
  • DAL
  • databases
  • DDD
  • DDD Coaching
  • DDD Domain Events Auditing nHibernate
  • DDD Entities Value Objects
  • Debugging
  • Design Patterns
  • Design Patterns Databases Auditing
  • Developement
  • Development
  • Development Coding
  • Development Process
  • Development unit testing
  • Development VS 2011
  • Diagnostics
  • Disposable
  • Exceptions
  • FINDaPAD
  • FindaPad Property Rental Windows Phone 7 Mobile Devices
  • Fun Coding Duct-Tape
  • Hotfixes
  • integration testing
  • IoC
  • jasmine
  • javascript
  • Jobs Development
  • LINQ
  • marketplace
  • Mobile Devices
  • Mocking
  • MSDN Coding
  • MSpec
  • Multilingual
  • MVC
  • MVVM
  • nCrunch
  • nHbiernate Repository Pattern Criteria
  • nHibernate Auditing Design Fluent
  • nHibnerate Entities Events Listeners
  • node.js
  • nodes.js
  • Nokia
  • NoSQL RavenDB Azure Development
  • Observations
  • OO
  • ORM
  • Performance
  • Portable Class Library
  • Portable Library
  • PostSharp
  • Process
  • Rants
  • RavenDB IIS 7.5 Development
  • Reactive
  • Reactive Extension
  • Reactive Extensions
  • ReadOnlyCollections
  • Resharper
  • REST Distributed-Systems
  • REST HTTP
  • rest web
  • RESTful
  • Rx
  • Serialization
  • Silverlight
  • Silverlight Installation
  • Task
  • TDD
  • TDD IoC DI
  • TDD Mocking
  • TDD Team Observation
  • Telerik
  • testing
  • threading
  • TPL
  • UI
  • Undo-Redo
  • unit testing
  • ViewModels
  • VS 2012
  • wcf
  • web api
  • Web Services
  • web services mobile devices data
  • WebAPI
  • Windows
  • Windows 8
  • windows phone
  • Windows Phone 7
  • WP7
  • WP7 Bing Maps Development Network HTTP
  • WP7 Bing Maps Development UK Crime
  • WP7 Bing Maps Development UK Crime Clustering
  • WP7 Bing Maps Development UK Polygons Clustering Performance
  • WP7 cryptography bouncy castle
  • WP7 Cultures C#
  • WP7 feedback development app store
  • WP7 Javascript web browser
  • WP7 MSBuild
  • WP7 ORM Databases performance
  • WP7 Serialisation
  • WP7 SilverlightSerializer C#
  • WP7 sqlite performance development
  • WP7 WP7Contrib Bing Maps Development
  • WP7 WP7Contrib Bing Maps Polygon Development
  • WP7 WP7Contrib CodePlex
  • WP7 WP7Contrib CodePlex Bing Maps Development
  • WP7 WP7Contrib CodePlex ObservableCollection
  • WP7 WP7Contrib ILMerge .Net
  • WP7 WP7Contrib Phone Maps
  • WP7 WP7Contrib SilverlightSerializer C#
  • WP7Contrib
  • WP7Contrib Bing Maps WP7
  • WP7Contrib WP7 Geo-Location development C#
  • WP7Contrib WP7 HTTP Compression
  • WP7Contrib WP7 Url Development Rx
  • WP7Dev
  • WPF
  • WPF Cultures
  • WuApi
  • XAML

Blog Archive

  • ►  2013 (16)
    • ►  November (5)
    • ►  September (3)
    • ►  August (1)
    • ►  July (1)
    • ►  June (3)
    • ►  May (2)
    • ►  January (1)
  • ▼  2012 (44)
    • ►  November (2)
    • ▼  October (8)
      • Trying to be more functional with Rx
      • Building a simple Portable Class Library - Simple....
      • Tricky continuous testing and self hosting WebAPI ...
      • Exception handling for an async method
      • Self hosting a web service inside a test fixture u...
      • Using GetRequestStreamAsync and GetResponseAsync i...
      • Testing time based observable in Rx is so easy...
      • Using CompositeDisposable in base classes
    • ►  September (5)
    • ►  August (2)
    • ►  July (4)
    • ►  June (3)
    • ►  May (1)
    • ►  April (2)
    • ►  March (13)
    • ►  February (4)
  • ►  2011 (52)
    • ►  December (3)
    • ►  November (5)
    • ►  October (7)
    • ►  September (7)
    • ►  August (11)
    • ►  July (4)
    • ►  May (2)
    • ►  April (1)
    • ►  March (5)
    • ►  February (3)
    • ►  January (4)
  • ►  2010 (1)
    • ►  August (1)
  • ►  2009 (32)
    • ►  December (3)
    • ►  November (7)
    • ►  October (6)
    • ►  September (11)
    • ►  April (1)
    • ►  March (4)
Powered by Blogger.

About Me

Unknown
View my complete profile