Ensuring the integrity of an IoC container

by Geert 12. April 2013 00:18

Note that while this feature is implemented in Catel, the technology can be implemented by any IoC container. This feature is called "integrity checker" and will ensure you with useful information about type registration paths. This protection mechanism is very useful in complex applications. When people start building services, sometimes they accidentally inject other services that via injection to other services cause a stack overflow. Debugging and determining which type is causing the issue can be very time-consuming. To make the example a bit more simple, below are a few classes which demonstrate a common issue in enterprises.

   1:  public class X
   2:  {
   3:      public X(Y y) { }
   4:  }
   5:   
   6:  public class Y
   7:  {
   8:      public Y(Z z) { }
   9:  }
  10:   
  11:  public class Z
  12:  {
  13:      public Z(X x) { }
  14:  }

Note how a round-trip of dependencies is created which will result in a StackOverflowException somewhere in your code. Below is a graphical example what happens. Note that the dotted line is showing the circular dependency causing the StackOverflowException.

StackOverflowExample

TypeRequestInfo

The first step for the integrity checker is to make sure that it knows what types are being requested from the ServiceLocator (which will be instantiated by the TypeFactory if required). This class contains all the information about a type being created by the TypeFactory:

  • Type
  • Tag (optional, can be used to differentiate different instances of the same type registration)

TypeRequestPath

Now we have detailed information about the types being constructed, it is very important to keep track of the types which are being created by the TypeFactory. During the construction of a type, the TypeFactory will request the ServiceLocator for a type, which will ask the TypeFactory to construct the type again. Each time the TypeFactory starts constructing a type (and currently has a TypeRequestPath), it will create a new instance of the TypeRequestInfo and add it to the TypeRequestPath. The diagram below shows how the TypeRequestPath will evolve.

Evolving of the TypeRequestPath

Once the TypeRequestPath will contain a duplicate instance of a TypeRequestInfo, it will become invalid (which means there is a circular type dependency).

Note that this is a very simple example, but normally a type will have several services injected which can have dependencies on their own as well which can cause a very complex type request path

Checking the integrity of the type request

To resolve and construct a type, a lot of communication will happen between the TypeFactory and the ServiceLocator. This flow is show in the diagram below.

ServiceLocatory and TypeFactory communication

As you can see, there is a lot of communication between the ServiceLocator and TypeFactory. In the TypeRequestPath example we already saw how the path will become invalid when it contains a duplicate instance of the TypeRequestInfo. The TypeRequestPath will then throw a CircularDependencyException with all the necessary information to solve the issue:

image2013-4-12 0-8-3

Now you will find the issue in no-time and save yourself a lot of your valuable time!

Tags:

C# | Catel | IoC

Subscribing to change notifications without memory leaks

by Geert 1. March 2013 22:11

You know this feeling? You are doing the best you can to prevent memory leaks by correctly unsubscribing from all events, and then you hit that object from which you cannot determine the lifetime. Well, you have a few options:

  1. Don’t talk about it, maybe your app won’t be used that much so maybe nobody notices.
  2. Try to implement IDisposable, but when to call that, you don’t know the end of life of the object?
  3. Fix the issue, but how?!

Note that this solution works on .NET, Silverlight, Windows Phone and WinRT. It doesn’t matter whether you use ASP.NET MVC, MVVM in WPF of your own custom pattern.

How do I create a memory leak?

Creating a memory leak is very easy. Simply subscribing to change notifications of objects mostly results in large statements such as the one below:

   1:  var itemAsPropertyChanged = obj as INotifyPropertyChanged;
   2:  if (itemAsPropertyChanged != null)
   3:  {
   4:      itemAsPropertyChanged.PropertyChanged += OnPropertyChanged;
   5:  }

 

What is the solution to prevent memory leaks?

You can either use the WeakEventListener in Catel or use the brand new ChangeNotificationWrapper that is now available in the latest prerelease version of Catel on NuGet. The ChangeNotificationWrapper allows the subscription of both the INotifyPropertyChanged and INotifyCollectionChanged interfaces using weak events, thus preventing memory leaks.

Subscribing to events of an observable object

Using the code below, one can subscribe to the PropertyChanged event of an object:

   1:  var wrapper = new ChangeNotificationWrapper(obj);
   2:  wrapper.PropertyChanged += OnPropertyChanged;

Note that it is not required to check whether the object implements INotifyPropertyChanged, the wrapper does it automatically

Subscribing to events of an observable collection

Using the code below, one can subscribe to the CollectionChanged event of an object:

   1:  var wrapper = new ChangeNotificationWrapper(observableCollection);
   2:  wrapper.CollectionChanged += OnCollectionChanged;

Note that it is not required to check whether the object implements INotifyCollectionChanged, the wrapper does it automatically

Advanced scenario with observable collections

Sometimes it is required to watch both changes inside a collection, but also the items inside a collection. For example, there is a list of customers and you are also interested in changes of customers inside a collection. This is fully supported by the ChangeNotificationWrapper using the code below:

   1:  var wrapper = new ChangeNotificationWrapper(observableCustomerCollection);
   2:  wrapper.CollectionChanged += OnCollectionChanged;
   3:  wrapper.CollectionItemPropertyChanged += OnCollectionItemPropertyChanged;

All subscriptions are automatically managed by the ChangeNotificationWrapper when items are added or removed from the collection.

Unsubscribing from events

When you are no longer interested in events from the source object, there are two options:

  1. Just leave them coming, as soon as the objects are no longer used, they will be garbage collected
  2. Unsubscribe using the following code:
   1:  wrapper.UnsubscribeFromAllEvents();


Grabbing the bits

As always, Catel is open-source thus you can either check out the source or grab the latest bits via NuGet.

Tags: , ,

C# | Catel

Entity Framework Unit of Work and repositories

by Geert 27. February 2013 20:11

Catel is an application development platform for C# that was primarily focused on xaml languages (WPF, Silverlight, Windows Phone). The core however is usable by server implementations as well and more and more extensions are being developed. This blog post will give an introduction to the Unit of Work and the repositories that are available in Catel.

Overview of Unit of Work and repositories

The Repository and Unit of Work (UoW) pattern are very useful patterns to create an abstraction level over the DbContext that is provided by Entity Framework. A much heard excuse not to use repositories is that EF itself already works with repositories (the DbContext) and a UoW (in the SaveChanges method). Below are a few examples why it is a good thing to create repositories:

  • Abstract away some of the more complex features of Entity Framework that the end-developer should not be bothered with
  • Hide the actual DbContext (make it internal) to prevent misuse
  • Keep security checks and saving and rollback in a single location
  • Force the use of the Specification pattern on queries

A Unit of Work (UoW) is a a combination of several actions that will be grouped into a transaction. This means that either all actions inside a UoW are committed or rolled back. The advantage of using a UoW is that multiple save actions to multiple repositories can be grouped as a unit.

A repository is a class or service responsible for providing objects and allowing end-developers to query data. Instead of querying the DbContext directly, the DbContext can be abstracted away to provide default queries and force required functionality to all end-developers of the DbContext.

A Unit of Work (UoW) is a a combination of several actions that will be grouped into a transaction. This means that either all actions inside a UoW are committed or rolled back. The advantage of using a UoW is that multiple save actions to multiple repositories can be grouped as a unit.

A repository is a class or service responsible for providing objects and allowing end-developers to query data. Instead of querying the DbContext directly, the DbContext can be abstracted away to provide default queries and force required functionality to all end-developers of the DbContext.

image

The image above shows that the Unit of Work is the top-level component to be used. Each UoW contains its own DbContext instance. The DbContext can either be injected or will be created on the fly. Then the UoW also contains repositories which always get the DbContext injected. This way, all repositories inside a UoW share the same DbContext.

The DbContextManager

The DbContextManager class allows the sharing of DbContext (with underlying ObjectContext) classes in Entity Framework 5. The good thing about this is that the same context can be used in the same scope without having to recreate the same type of the same context over and over again.

   1:  using (var dbContextManager = DbContextManager<MyEntities>.GetManager())
   2:  {
   3:      var dbContext = dbContextManager.DbContext;
   4:   
   5:      // TODO: handle logic with dbContext here
   6:  }
 

Creating a Unit of Work

A UoW can be created by simply instantiating it. The end-developer has the option to either inject the DbContext or let the DbContextManager take care of it automatically.

   1:  using (var uow = new UnitOfWork<MyDbContext>())
   2:  {
   3:      // get repositories and query away
   4:  }


Creating a repository

A repository can be created very easily by deriving from the EntityRepositoryBase class. Below is an example of a customer repository:

   1:  public class CustomerRepository : EntityRepositoryBase<Customer, int>, ICustomerRepository
   2:  {
   3:      public CustomerRepository(DbContext dbContext)
   4:          : base(dbContext)
   5:      {
   6:      }
   7:  }
   8:   
   9:  public interface ICustomerRepository : IEntityRepository<Customer, int>
  10:  {
  11:  }

 

Retrieving repositories from a Unit of Work

Once a UoW is created, it can be used to resolve repositories. To retrieve a repository from the UoW, the following conditions must be met:

  1. The container must be registered in the ServiceLocator as Transient type. If the repository is declared as non-transient, it will be instantiated as new instance anyway.
  2. The repository must have a constructor accepting a DbContext instance

To retrieve a new repository from the UoW, use the following code:

   1:  using (var uow = new UnitOfWork<MyDbContext>())
   2:  {
   3:      var customerRepository = uow.GetRepository<ICustomerRepository>();
   4:   
   5:      // all interaction with the customer repository is applied to the unit of work
   6:  }

 

Saving a Unit of Work

It is very important to save a Unit of Work. Once the Unit of Work gets out of scope (outside the using), all changes will be discarded if not explicitly saved.

   1:  using (var uow = new UnitOfWork<MyDbContext>())
   2:  {
   3:      var customerRepository = uow.GetRepository<ICustomerRepository>();
   4:   
   5:      // all interaction with the customer repository is applied to the unit of work
   6:   
   7:      uow.SaveChanges();
   8:  }

 

Getting the assemblies and/or code

You can either get the assemblies via NuGet or view the source on codeplex.

Tags: , , , , ,

Catel | C# | Entity Framework

Catel 3.4 is released!

by Geert 15. December 2012 16:43

It has been quite a while, but today a new version of Catel is released. It took us more time then usual, but in return we have a great version ready to be downloaded via the site or via NuGet.

Added WinRT and Windows Phone 8 support

This is probably the most noticeable “feature” of all. Both WinRT and Windows Phone 8 are fully supported with all features that you are familiar with in Catel. This means that we were able to port everything (not really everything, but 90 %) of it to WinRT and all known Windows Phone features to Windows Phone 8.

Performance improvements

For this release, we focused on performance. We made a lot of improvements by tracing and tweaking all the calls thoroughly. Below is a list of tweaks:

  • All reflection calls are now being cached
  • Logging is only executed when there are actually listeners registered
  • ModelBase.LeanAndMeanModel property to (temporarily) suspend both validation and change notifications, great when restoring models from disk
  • Added a FastObservableCollection which allows the adding of a range and only invokes a single event at the end
  • It is now possible to control (globally or per control) whether InfoBarMessageControl and WarningAndErrorValidator controls must be created or MVVM controls
  • Constructors in the ServiceLocator are cached which gives a major performance boost when creating new instances of types with dependency injection

Improved IoC container

The IoC container in Catel, the ServiceLocator, now supports registration of types with a tag. This allows the same type to be registered multiple times.

And much more…

Besides new features, we also fixed over 40 issues in this new release. Not all new features are described in this blog post, so make sure you get the latest version while it’s hot!

Tags:

MVVM | C# | Catel | Windows Phone 7 | Windows Phone 8 | WinRT | WPF | Silverlight

Showing a busy indicator per view in Silverlight using MVVM

by Geert 12. October 2012 10:03

Introduction

When using Silverlight, everything is asynchronous. It seems to be the trend, the same goes for Windows 8. This means that you will need to inform the user about progress in the background.

Silverlight uses the BusyIndicator for this behavior. Using MVVM, it might be a bit harder to implement the BusyIndicator in a correct way, but Catel provides the IPleaseWaitService for years which can be mocked easily during test scenarios.

However, it didn’t support a busy indicator per view yet. This fact has changed today, as you can see in the screenshot below:

image

A long requested feature in Catel was the support for tags in the ServiceLocator. The ServiceLocator is the IoC solution that Catel provides by default. A customer of Catel recently required the busy indicators to show up per view. I thought a bit about it and this could be solved by the recently (read: this week) introduction of the tags in the ServiceLocator.

Setting up the views

The view is responsible for registering the service. This can easily be done using the Catel user controls. Create a view like you always do, then use the following code-behind:

   1:  protected override void OnViewModelChanged()
   2:  {
   3:      var serviceLocator = ServiceLocator.Default;
   4:   
   5:      var viewModel = ViewModel;
   6:      if (viewModel != null)
   7:      {
   8:          serviceLocator.RegisterInstance(typeof (IPleaseWaitService), new PleaseWaitService(this), viewModel);
   9:      }
  10:  }

This code will be executed when the ViewModel property of the control changes. The view registers a view specific instance of the PleaseWaitService service in the ServiceLocator. It uses the new view model as tag so that will be used to distinguish the services.

Setting up the view models

The view model can retrieve the PleaseWaitService very easily because the tag is itself. To show the view specific please wait service, use this code:

   1:  var pleaseWaitService = GetService<IPleaseWaitService>(this);
   2:  pleaseWaitService.Show();

To hide the window again, use this code:

   1:  var pleaseWaitService = GetService<IPleaseWaitService>(this);
   2:  pleaseWaitService.Hide();

 

Customizing the PleaseWaitService

Customizing the please wait service is very, very easy. Just override the class like this:

   1:  public class MyCustomPleaseWaitService : PleaseWaitService
   2:  {
   3:      protected override FrameworkElement CreateBusyIndicator()
   4:      {
   5:          var busyIndicator = new MyBusyIndicatorControl();
   6:          
   7:          busyIndicator.SetBinding(System.Windows.Controls.BusyIndicator.BusyContentProperty, new Binding("Status"));
   8:          busyIndicator.SetBinding(System.Windows.Controls.BusyIndicator.IsBusyProperty, new Binding("IsBusy"));
   9:          
  10:          return busyIndicator();
  11:      }
  12:  }

The base implementation will automatically take care that the data context is updated and that the control is centered as required.

Demo and source

Last but not least, here is a demo and the source.

PleaseWaitServicePerView.zip (21.24 kb) [Downloads: 455]

Tags:

C# | Catel | MVVM | Silverlight


About the Author

Geert van Horrik is an independent freelance software developer since January 1st, 2007. Since then he was been working on several projects from C++ to C# (WPF, Silverlight, ASP.NET, etc). Currently he loves to write his software using WPF (or Silverlight if WPF isn't an option).

Lately, Geert is spending a lot of time on Catel, a free open-source MVVM Framework for WPF and Silverlight. Actually, it's more than "just" an MVVM Framework, it's a complete application library!