Latest Tweet:
  • Loading...

There has been lots of talk in the Silverlight community about what is the best way to implement the INotifyPropertyChanged interface. During Christmas I blogged about how you can use dynamic proxies to get INPC implemented automatically. Since then both Einar Ingebrigtsen and Justin Angel have blogged about an interesting approach to INPC using MSIL weaving. I really recommend checking out Justin’s post, as he covers some of the pros and cons of different INPC implementations, as well as purposing an elegant solution using post-build MSIL weaving.

One of the things Justin mentions as a drawback of the dynamic proxy approach is that you cannot simply new up your ViewModel directly and get change notification automatically. You have to explicitly create the ViewModel instance through a proxy creator. Einar also mentioned that he had a hard time finding a way to integrate the proxy creator with an IoC container.

When I write code I’m always careful about where I instantiate my objects, and lately all projects I’ve worked on have used some sort of IoC container. Having an IoC container gives you a single place in your code base to create- and register objects. If the dynamic proxy implementation of automatic INPC is going to be useful it has to be as simple requesting a ViewModel instance from the IoC container. In this blog post I’m going to show how you can combine automatic INPC using dynamic proxy with the Ninject IoC container.

If you have read my blog you may have noticed I got a soft spot for Ninject. I mean, who cannot love a framework whose name, graphic profile and code examples are all about Ninjas? When I first set out to integrate my automatic INPC interceptor with Ninject I wasn’t quite sure where to start. Ninject 1.0 had AOP concepts built in, but in 2.0 (which are under development) this has been moved out of the core and into a separate interception extension module. This is part of the new modular design of Ninject 2.0. Features you may not need all the time are moved out to separate extensions, leaving the core really small and simple (~90kb).

ninject-ninja

My first plan was to use the Ninject interception extension. The extension uses the LinFu framework for dynamic proxies, and I wasn’t sure how to get my Castle Dynamic Proxy based implementation to work directly. I later got contacted by Ian Davis, the owner of the interception-extension project. He asked if I needed some help getting automatic INPC working with Ninject. After some back-and-forth on Twitter Ian had an implementation of automatic INPC added to the Ninject.Extension.Interception project. The code is commited to the trunk, and is available on github if you want to check it out. Ian’s implementation is probably worth a blog post on its own.

A comment from Miguel Madero pointed me in the right direction to get my interceptor working with Ninject. Miguel had integrated it himself by implementing the interceptor as a Ninject Provider. Ninject lets you register types against providers which let you write code that creates the instance when the type is requested from the container. The interface is really simple, having one Create-method. In this method you have to create the instance being requested.

The implementation for the automatic INPC provider is fairly simply. It finds the largest constructor of the ViewModel being requested, creates instances of all constructor parameters, before calling the dynamic proxy creator I implemented in my previous two blog posts.

ProviderCode

In Ninject all configuration is done through code using an internal DSL. You configure the container by creating module classes specifying the bindings of the different types you want to be able to create. In this example I have a simple logging service (to demonstrate constructor injection combined with automatic INPC) as well as a simple ViewModel. The ViewModel is bound to the provider, which will call the proxy creator when the ViewModel is requested.

ConfigurationExample

This unit tests shows how to request an instance of the ViewModel from the container. When the Name-property is set the ViewModel will log the action to the fake logger which was injected into the ViewModel constructor.

ExampleUnitTestOfViewModelFromKernel

Having to register every single ViewModel against the provider is tedious and repetitive. Miguel Madero also suggested that you can override the GetBinding method of the Ninject StandardKernel and use convention over configuration. By overriding the GetBinding method we can check if the type being requested is a ViewModel, and if it is we can create a binding on the fly tying the ViewModel type against the automatic INPC provider.

The implementation of the AutoNotifyKernel is really simple. It checks if the name of the type being requested contains “ViewModel” and implements the IAutoNotifyPropertyChanged interface. If it does we create a binding for the type.

AutoNotifyKernel

Having a convention based approach in place we do not have to manually register every single ViewModel.

Some of this code might seem complicated, but I really wanted to cover the details of how to integrate it with Ninject, as similar approaches probably work for other containers. Once you got a framework for automatic INPC in place the usage becomes really simple. In the example application for automatic INPC the code needed to implement the ViewModel, configure the container and tie the ViewModel to the View looks something like this:

FullExample

It’s funny how such a simple interface can trigger so many different implementations. I hope you found my blog post on combining a dynamic proxy approach with an IoC container useful. It will be interesting to see which approach emerges as the most used, and which frameworks that will provide implementations of the different techniques.

Adobe Kuler is a great example of a Rich Internet Application that provide great value directly in the browser. Kuler is a tool that helps you create color themes by applying different rules to find matching colors. You start by selecting a base color, and Kuler will help you find four matching colors. You can even use Flickr photos as a basis for your color theme. Adobe Kuler has a social aspect to it as well. You can create an account and save your colors online and share them with the community. People can rate and commend on your themes, or create new color themes based on an excising one. Kuler is being a good Web 2.0 citizen and offers a REST-full API that lets you build your own applications using the colors of the community.

Screenshot of Adobe Kuler

Whenever I find a service I like with an open API I just can’t leave it alone. So today I’m announcing the Colorful Expression add-In.

Colorful Expression is an add-in for Expression Blend and Expression Design that brings you the Adobe Kuler community directly into your toolbox. It adds a new palette to your design environment, making it easy to leverage the community to find the perfect color theme for your application or design. The add-in also available as a standalone application, making it useful for web developers working in Visual Studio or Expression Web to select colors for your CSS style sheets.

Expression Design

Last week Jose Fajardo blogged and complained that Expression Design doesn’t get enough love. I totally agree, and am going to give it some love by making it more colorful.

Expression Design AddIn 

The key feature of the add-in is to select colors. The eyedropper tool in Design lets you click anywhere on the screen to select a color. Simply click the eyedropper in your color panel, and click on one of the colors in the Colorful Expression panel.

You can also copy colors to the clipboard by clicking the copy-button. When you paste the color theme onto the design surface you’ll get five rectangles and the name of the color. This lets you collect interesting themes directly in your design file by copying them onto the document.

Expression Blend supports exporting and importing color swatch libraries through a simple XML file format. Colorful Expression allows you to save a theme as a swatch library you can import into Design. The screenshot shows the “Buddah in Rain” theme imported to the swatch library.

Expression Design AddIn Screenshot

Expression Blend

The add-in works almost the same way in Blend as in Design but with some minor differences. In Blend you can use the Ctrl+C key combination to invoke the copy command, making it a lot easier to copy/paste themes onto the design surface. When you paste a theme onto the surface you will get a grid containing five rectangles and a text block. The rectangles are painted with a solid color brush resource, and each of the colors gets added to the resource collection of the page. If you go into XAML-view and paste the theme you will get five solid color brush resource elements you can add to any resource collection. The Blend add-in also supports drag and drop, letting you drag color themes onto the design surface.

Blend add-in screenshot

Standalone application

The standalone application gives you most of the same features as the Blend and Design add-in. You can copy or drag themes into Blend, and you can save Design swatch libraries. The stand alone application is useful if you don’t want to run the add-in all the time or if you don’t use Expression Studio. You can also hold down control and click a single color to copy it to the clipboard as a RGB HEX color. That way you can use the standalone application as a color picker for any application using HEX colors, such as CSS style sheets.

Standalone application screenshot

Ideas for next version

I want to keep the add-in simple and focused, but I do have some ideas for new features. The first thing I’m planning to implement is a color provider for the COLORLovers site. I also want deeper integration with Blend and Design, especially around managing resources in Blend.

It would also be nice to support Expression Web and Visual Studio 2008 so that web developers can use it to get CSS colors for their web projects.

Another feature missing is support for the light Expression Studio color theme. The current look and feel is based on Hadi Eskandari’s Expression Clone theme and only supports the dark theme. It should be fairly simple to create a new theme matching the light colors.

You can suggest new features in the discussion board or report bugs in the issue tracker.

Download and installation

The project is released on http://www.codeplex.com/colorful, and the initial release contains the compiled version of the add-in for Design 2.0, Blend 2.0, Blend 2.5 June CTP, Blend 2.0 SP1 Preview and as a standalone WPF application. To install the add-in simply copy the files into your Blend or Design director, and launch the EXE file with an extra parameter.

I.e: “Blend.exe –addin:Colorful.Blend.AddIn.dll” or “Design.exe –addin:Colorful.Design.AddIn.dll”.

You can also right click your application shortcut and select properties to change the target of the shortcut. Add the above parameters to the target to launch Blend or Design with the add-in every time you click the shortcut.

ShortcutProperties

Getting involved

If you would like to get involved in the project drop me an e-mail at jonas@follesoe.no. You can also suggest features or report bugs in the discussion forum and the issue tracker.

To build the project you need to have Expression Blend or/and Expression Design installed. The add-in has a dependency on Microsoft.Expression.Framework.dll, which in turn has a dependency on Microsoft.Expression.Diagnostics.dll, Microsoft.Expression.Interop.dll and Microsoft.Expression.Licensing.dll. For licensing reasons these assemblies are not checked into the source control three.

If you want to run the add-in from Visual Studio I recommend running Visual Studio 2008 as administrator and then change the output directory of your debug build to the installation folder of Blend/Design. Then change the startup application to the Blend.exe/Design.exe with the correct startup arguments. That way you can hit F5 inside Visual Studio to launch Blend/Design in debug mode. You can set breakpoints in your code and test/debug the add-in this way.

Happy coloring!

When building line-of-business (Smart Clients or Rich Internet Applications) you normally talk to some back-end web service responsible for enforcing business rules, authentication, and storing your data in some database. When implementing your client application you often end up re-implementing some of these business rules to give the user a better experience. Instead of having to pass an Order-object to the web service just to get an exception saying that the order date field is a required, you should try to enforce these validation rules directly in your user interface. How do you best implement these rules across your tiers?

Sharing is caring!

In his January 2004 MSDN article title "A Guide to Developing and Running Connected Systems with Indigo" Don Box presented four rules for connected systems, later often referred to as “the four tenets of SOA”. The rules are as following:

  • Boundaries are explicit
  • Services are autonomous
  • Services share schema and contract, not class
  • Service compatibility is determined based on policy

Especially rule number three is relevant when talking about implementing business rules on both server and client. In traditional object oriented design you would implement your domain- or business objects and let them encapsulate your rules and logic. One of the advantages of web services is that they work across boundaries and platforms. They also help you make your systems loosely coupled, only depending on the service contract and not a specific binary component. Web services use open standards such as HTTP, SOAP and XML to achieve interoperability and louse coupling.

Services do not deal in types or classes per se; rather, only with machine readable and verifiable descriptions of the legal "ins and outs" the service supports. The emphasis on machine verifiability and validation is important given the inherently distributed nature of how a service-oriented application is developed and deployed. Unlike a traditional class library, a service must be exceedingly careful about validating the input data that arrives in each message. Basing the architecture on machine-validatible schema and contract gives both developers and infrastructure the hints they need to protect the integrity of an individual service as well as the overall application as a whole. – Don Box

Blindly following the rule about not sharing class can lead to developers and architects forgetting what they know about object oriented design. This is something I have experienced on several projects. However, there is nothing in Don Box reasoning stopping you from building some really smart classes or libraries to help you consume and talk to these web services. Most development platforms have some sort of tool support to automatically generating proxies to create the SOAP messages needed to communicate with the service. However, since these classes are all generated based on WSDL and XSD definitions they don’t contain any "smarts", like validation rules, authorization, or computed properties.

There are different techniques to achieve sharing of some logic between server and client. An old trick is to move all your business entities into a separate assembly and use this on both server and client. After Visual Studio have generated a web service proxy you remove any generated types and include a using statement to the namespace containing your business entities. When the proxy de-serializes an Order-object from your web service it will create a "real" Order-object instead of an auto generated type. This object will have any validation rules or computed properties, which would be lost in the auto generated type. In Visual Studio 2003 and 2005 you had to do this by hand, which was bothersome, and something you had to redo every time you update your service reference. In Visual Studio 2008 this pattern is supported by the tool. When adding a new service reference you can choose to reuse any types in referenced assemblies, letting you use real objects instead of automatically generated proxy objects.

When working with Silverlight this is a little bit harder. The problem is that the client Silverlight .NET runtime is different from the server .NET runtime. You can’t directly reference a Silverlight class library in your web service application, or reference a traditional .NET class library in your Silverlight application. There are workarounds to help you share code between a .NET server application and a Silverlight client application. You can create two different class libraries, one for Silverlight and one for the server, and link the class files between them. You have one copy of the file, but it’s added to two different projects, letting you compile the same class into two different assemblies. Since Silverlight is a subset from .NET you may not be able to do all the same things in the client library as in the server library. You can separate out Silverlight and .NET specific code using compiler directives or partial classes.

#If Silverlight then 
	// Silverlight only code 
#Else 
	// .NET only code #End If 

This is the approach taken by Rockford Lhotka in CSLA Light, a trimmed down version for Silverlight of his CSLA.NET application framework. He recently started blogging about how CSLA Light helps you reuse business objects between tiers. This approach might be difficult if your server code have many external dependencies, for instance to ORM tools or other frameworks you don’t have a Silverlight version for.

Extending the automatically generated types

The web service proxies generated by Visual Studio have gotten better and better, and the classes generated by Visual Studio 2008 are quite useful. Sure, they won’t know about server specific rules, but the generated objects use properties, implements change notification and use observable collections for lists. This enables you to data bind against the proxy objects, which is really handy. However the solution isn’t perfect. One of the features added in Silverlight 2 Beta 2 is the support for binding validation. This enables you to detect if the data entered by the user in a data bound field breaks any validation rules. When the binding validation event fires you can highlight the field, for instance by changing background color. The way binding validation works in Silverlight 2 Beta 2 is by exceptions thrown in the setter of a property. If you bind against the automatically generated proxy objects you can’t change the setter to implement your validation rules.

Another example where you want to extend the proxy objects with additional functionality is for computed properties. Since I just got back from a dive trip I’m going to use that as an example. When logging a dive you enter date, time in water, bottom time and time out of water. If I were to implement a dive log application I would store the time the diver entered the water and the bottom time in the database. The time out of water would be a computed property, computed adding the bottom time (minutes) to the time the entered the water time. If I did this on my server, the data would get passed to the client, but the automatically generated proxy object would see this as any other "dumb" property. It wouldn’t understand the relationship between time-in water, bottom time and time-out of water. If I change the bottom time, the time out of water property wouldn’t change.

To solve these problems you have two options. You can choose to treat your web service objects as simple data transfer objects, and wrap them in your own custom client side objects. This can be done by creating a new DiveLogClient-object that takes the DiveLog proxy object in the constructor, and creates new properties for any field used by the UI. This approach gives you full flexibility but involves doing a lot of extra work. Another option is to create a partial class that extends the automatically generated proxy object. This class could add new properties, like TimeInClient, TimeOutClient and BottomTimeClient, which use the same private backing fields as the generated properties, but have additional logic needed to understand the relationship between time-in, bottom time and time-out. Your user interface would bind against the new properties instead of the generated properties, but since they use the same backing fields for their values you can still send the object back to the server to store any changes.

Is Microsoft doing anything to help?

Wanting to share some logic between the server and client is a common pattern. Surely Microsoft must be thinking about how they can help. By improving the service reference tool in Visual Studio Microsoft made it easier to share types across boundaries. But there is still allot that can be done. The Smart Client Software Factory contains functionality to map between service entities and business entities, which let you build richer business entities on the client, and get some framework support to map between the different types. But I’m sure they can do better…

Yesterday Microsoft announced 50 new session abstracts for PDC 2008 held in October. It’s really interesting to read the session abstract to get some ideas of unannounced products and project they are working. One of the sessions that caught my attention is "Microsoft Silverlight: Building Business Applications":

What if you could develop your solutions with the ease pioneered by Microsoft Office Access, deploy them like an Internet application, and take advantage of the power of Microsoft .NET? Learn about an exciting new technology that is all about making business applications for RIA (Rich Internet Applications) much easier to build. In this session, hear how we've made n-tier application development as simple as traditional 2-tier, provided application level solutions to developers, and how we're doing all of this with the same .NET platform and tools on both the client and server.

I guess it’s safe to assume that Microsoft have some really cool stuff in the works. Which approach they take to make n-tier development as simple as traditional 2-tier development I don’t know. But I wouldn’t be surprised to see some kind of smart sharing of linked code files, with partial classes or compiler directives to separate server and client code. It’s also interesting that SOA-expert Pat Helland has been working on a project in the area of RIAs, so hopefully he has been able to provide some valuable input on how to architect RIAs.

Which approach do I use?

Well, it depends… For larger Silverlight projects I tend to consider the automatically generated proxy objects as dumb data transfer objects that I wrap in business objects used by my Silverlight application. The advantage is that I get full control over the object, but the drawback is that I have to do more manual work… For smaller projects where I need minor changes I tend to use partial classes to extend the proxy objects with additional properties used by the client, but backed by the same fields as the properties that get serialized when sending the object back to the server. In the long run I’m a strong believer in tools or frameworks that help us reuse code between server and client in a clean way giving us something smarter than the proxies generated by Visual Studio. Frameworks like CSLA Light or the tools Microsoft will announce at PDC will probably help to deliver this. I expect the announcements at PDC to be to Silverlight what ASP.NET Dynamic Data is to web application. Dynamic Data lets you scaffold a complete data driven application, but without compromising customizability or generating tons of hard to maintain crappy code.

How do you share business logic between server and client?

In an earlier post this week I wrote about implementing the Model-View-ViewModel pattern in the YouCard application. In this post I’m going to build on that and implement Inversion of Control Containers and the Dependency Injection pattern. Lots have been written about dependency injection, so the focus of this post will be on using dependency injection in a Silverlight context, and specifically how to implement it using the Ninject framework. For an excellent introduction to the pattern I strongly recommend Fowlers essay on the topic.

When getting into dependency injection you might get intimidated by the number of frameworks available to help you implement the pattern. It might give you the impression that dependency injection is something big and complicated, which is going to have a huge impact on how you build your software. The later might be true, but not necessary because of the framework but rather by the flexibility gained by introducing this pattern. In its simplest form dependency injection is about how you supply external dependencies to your application classes. In the previous blog post I refactored the Twitter and Flickr integration into external classes that complies with an interface. Depending on if the code was executed inside Blend or the browser I either use the real implementation, or a mock implementation providing some dummy data at design time.

Code sample 1

The problem with the above code is the coupling between the YouCardData class and the four classes implementing the IMicroBlog and IPhotoService interfaces. This high level of coupling between the view-model (YouCardData) and its external dependencies (Twitter and Flickr) makes the code less flexible. Coding against interfaces enables me to implement other services, such as a Picasa photo service, or a Tumblr micro blog service. The problem is how I get the YouCardData class to use these alternative implementations. The code is also hard to unit test as I can’t provide a mock implementation of the external services. We could refactor our code to take the external dependencies as constructor parameters like this:

Code sample 2

By doing this we allow the consumer of the YouCardData class to inject the external dependencies through the constructor. And in essence this is constructor based dependency injection, by hand. The above change gives us greater flexibility to provide alternative implementations of the services, either for testing purposes, or to provide new functionality. But there is still a problem with the code. If you want to create an instance of the class from XAML, for instance when setting the data context, a default parameter less constructor will be used. You could solve this limitation by adding an additional constructor like this:

Code sample 3 

This would solve the XAML problem, as any instance crated declaratively would use the Twitter and Flickr implementation, but for testing purposes we could provide our own mock implementation. But the solution still isn’t perfect. In the first constructor we had code to check if the class was consumed inside Blend or not. Depending on this we used different implementations of the external services. We could have kept this constructor, but instead we’re going to use an Inversion of Control container to help us build our objects.

Ninject

Lately I’ve been doing some research on UI frameworks and patterns, and many of these use some sort of dependency injection framework. The Prism-AG framework, a Silverlight port of the Composite WPF framework, uses a small dependency injection framework called DLLite. Another dependency injection ported to Silverlight is Unity, another framework from the Microsoft patterns and practices group. But my personal favorite so far is Ninject, the ninja of dependency injection. This framework caught my attention after listening to Nate Kohari in episode 5 and 6 of the AltDotNet podcast. Ninject describes itself the following way:

Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.

You shall feel my wrath as I rip you apart to inject my powers into you!

The footprint of the compiled framework is only 110KB, and you only need a single reference to Ninject.Core.dll too getting what you need in most scenarios. Strength of Ninject is the focus of configuration through code instead of XML. Most other IoC containers have a strong emphasis on XML based configuration of object dependencies. This has its advantages if your deployment environment varies a lot between installations, but in many cases this adds additional configuration pain.

  1. Your configuration can get more complex and verbose since you often have to write out fully qualified assembly names for each type.
  2. Its easer to break the application through simple typing mistakes.
  3. If the rules describing how to write your application together gets complex this might be hard to express through XML.

In comparison, Ninject uses a fluent interface, or sometimes referred to as "embedded domain-specific language". This lets you take advantage of the programming language to build up the wiring of your application. You can express complex rules of how the wiring should happen, and there is nothing stopping you from writing code that reads a configuration file if some of the wiring depends on user configuration.

"… There are cases where it’s easier to use program code to do the assembly. One case is where you have a simple application that’s not got a lot of deployment variation. In this case a bit of code can be clearer than separate XML file.

A contrasting case is where the assembly is quite complex, involving conditional steps. Once you start getting close to programming language then XML starts breaking down and it’s better to use a real language that has all the syntax to write a clear program.

…My advice here is to always provide a way to do all configurations easily with a programmatic interface, and then treat separate configuration file as an optional feature. – Martin Fowler"

Another cool aspect of Ninject is that it support Silverlight “out of the box”, and is not a port or a trimmed down version of a larger framework. Ninject was small to begin with.

Dependency Injection with Ninject

Adding Ninject support is fairly straight forward. The first thing we need to do is add is marking all constructors that take the dependencies, and mark it with a simple attribute.

Code sample 4

We also want to inject a persistence service into the main page view-model, the one controlling all the cards on screen. The persistence service is used to store all the users added, so that we don’t have to add them again when we come back to the application.

Code sample 5

If we use the Twitter service implementation we also want to inject a proxy URL. This is because Twitter doesn’t allow cross-domain callers and we need to proxy the request through our own server.

Code sample 6

The next thing we need to do is to wire the view-models to the services they need. In many IoC containers this is done through XML configuration, but in Ninject this is done through code and a fluent interfaces. Ninject uses a concept of modules to wire things together. One kernel (the container) can host multiple modules. For the YouCard application we need only one module.

Code sample 7

The benefit of fluent interfaces is increased readability of the code, so I’m not going to spend too much time describing the class line by line. The class derives from StandardModule, and overrides the Load method. In the Load method we set up the binding between the services and the concrete types. If you read the binding as “English”, from left to right, the binding rules should be fairly straight forward. Also worth notice is how I take advantage of configuration through code when I decide which implementation to use when the code is running inside Blend. I add a condition saying that the Twitter service should be used when executing inside the browser, while the mock service should be used from Blend.

To use the module I simply have to create a Ninject Kernel and pass it the module.

Code sample 8 

Notice how I don’t have to worry about constructing the YouCardData object. The kernel takes care of instantiating the object, and injects any dependency based on the bindings configured in the YouCardModule.

Data binding to objects built by Ninject

Now that we have configured our Ninject kernel the next challenge is getting our view-model objects out of the kernel and into the views, without breaking the design time experience in Blend. Setting the data context through code would be fairly simple. We could create the kernel in the application class, and then get it doing something like this.

Code sample 9 

That would enable us to have one kernel for the application (something you typically do). But it still wouldn’t solve how to set the data context of a user control to view-model built by Ninject, using declarative XAML code. This troubled me for a few days, and after thinking it through, trying some different approaches, and talking discussing it with Nate Kohari the solution turned out to be Service Locators. This is a different pattern used to implement Inversion of Control, and often you decide to use either service locators or dependency injection. I recommend reading the section on service locators vs. dependency injection in Fowlers essay for a good description of the pattern.

The short version of the pattern is that a service locator is a registry holding references to all the services used by your application. A class, such as the view-models in YouCard, can ask the service locator to give them an implementation of IPhotoService or ITwitterService. The big difference between service locators and dependency injection is that with SL your classes asks for an implementation, but with DI they are given an implementation (pull vs. push). Nate has blogged about how Ninject plays nicely with service locators.

"I don’t think that service locators and dependency injection are mutually exclusive; in fact, I’ve found that it can actually be very effective when used in conjunction with a dependency injection framework like Ninject. – Nate Kohari"

The service locator I’ve created for YouCard is fairly straight forward.

Code sample 10

In many cases you implement the service locator as a static class. That was not an option, as Silverlight 2 doesn’t support data binding to static classes. The way I solved this was to make a static constructor, and a private, static kernel field. The static constructor is the first thing executed in the class, before any standard constructors. The static constructor checks if we have a kernel and if not it instantiates one using module containing our binding configuration. By making the kernel field static we can ensure that we have only one instance of it in our application. The class has two instance properties that surface our view-models from the kernel, as well as a generic instance method to get any object from the container.

Before introducing dependency injection we bound our views to the view-model declaratively like this:

Code sample 11

After introducing a service locator we need to change this around a little. The first thing we do is to instantiate the service locator as an application level resource:

Code sample 12

Then for each of the views we need to change how they get their data context.

Code sample 13

Each of the views gets their view-model by data binding to properties on the service locator. The coolest thing about this approach is that we still get full Blend design time support with sample data provided through the mock services.

Conclusion

Introducing dependency injection in Silverlight isn’t any harder than in other .NET applications. The strong focus on keeping the framework light weight and extremely fast makes Ninject a perfect fit for Silverlight. However, one could argue that for a simple example like this Ninject isn’t really necessary. I could hand-write the dependency injection code inside my service locator, and eliminate the Ninject dependency, and still get the flexibility of dependency injection. On the other hand, Ninject is only 110KB (before it’s zipped into the XAP file), and isn’t going to add a lot of download weight to your application. 100KB is less than half the size of the images used as illustrations in this blog post...

Seperation of Concerns - The way of a true master

By using dependency injection you keep your code more flexible and testable, something that is just as important for Silverlight applications, perhaps even more, are UI requirements are likely to change a lot as you discover the power of Silverlight. I strongly believe in providing designers with a best possible experience inside Blend, and there is no reason for dependency injection to change that.

Microsoft is doing an "Expression European Design Tour" this fall, and is visiting Oslo October 12. It's an half day event (including lunch), and best of all: it's free! The speakers are Surya Vanka, Florent Bajani and Martin Trion. During the event they'll cover stuff like Microsofts propositions in the design space, the social media revolution and designing rich client experiences. Click to read more about the event, the speakers and how to sign up.

expressioneuropeantour.jpg

<September 2010>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789