Click here to Skip to main content
Licence CPOL
First Posted 31 Aug 2009
Views 3,631
Bookmarked 0 times

Wpf Ninject Dojo: The Data Provider

By | 31 Aug 2009 | Technical Blog
You have probably heard me go on about Unity a couple of times: My.Unity.Resolve(Of Ninja) Unity and ASP.NET Creating a Data Access layer using Unity I have been using what is now unity since the good old days (sooo not true, WPF is the Windows Forms killer, and good riddance) of Windows
A Technical Blog article. View original blog here.[^]

You have probably heard me go on about Unity a couple of times:

I have been using what is now since the good old days (sooo not true, WPF is the Windows Forms killer, and good riddance) of WindowsForms and CAB (Client Application Block), but now there is a lightweight alternative: .

I decided on my latest project (a Wpf dashboard for HEAT ITSM) that I needed dependency injection. Whenever I start building a project I always end up needing some sort of dependency injection to keep everything nice and neat. It is only really needed once you get to a certain size and when you start wanting talk between ViewModels.

Anyway I was using a method of injecting my ViewModels into the Views using standard binding:

<igDock:ContentPane x:Class="SlaTodayView"
    xmlns:igDP="http://infragistics.com/DataPresenter"     
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:local="clr-namespace:WpfHeatItsmDashboard"
    xmlns:igWindows="http://infragistics.com/Windows"
    xmlns:igDock="http://infragistics.com/DockManager"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Header="Sla Today" MinWidth="30" MinHeight="50">
    <igDock:ContentPane.Resources>
        <ObjectDataProvider 
        x:Key="ViewModel" 
        ObjectType="{x:Type local:SlaTodayViewModel}" 
        />
    </igDock:ContentPane.Resources>
    <igDP:XamDataGrid DataContext="{StaticResource ViewModel}" DataSource="{Binding Calls}" Theme="Office2k7Black" >

    </igDP:XamDataGrid>
</igDock:ContentPane>

But once you move to dependency injection you do not want to keep all those fixed object definitions. These may become interfaces, or you may just want to replace, or dynamically replace, one of these types by a derived one at runtime.

That being the goal, we need some way to retrieve that type even in design mode. There is nothing worse than components or bits of components that make it difficult to work in both Visual Studio and Blend, and with the new binding features of Visual Studio 2010 for WPF 4 it will be even more important that your usage is as compatible as possible.

What I decided to do was create a custom called the NinjectDataProvider that I could use instead of the ObjectDataProvider. This is the first version of that provider and it does nothing more than retrieve the type form the Kernel. Minimal changes to the WPF enable this:

<igDock:ContentPane x:Class="SlaTodayView"
    xmlns:igDP="http://infragistics.com/DataPresenter"     
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:local="clr-namespace:WpfHeatItsmDashboard"
    xmlns:igWindows="http://infragistics.com/Windows"
    xmlns:igDock="http://infragistics.com/DockManager"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Header="Sla Today" MinWidth="30" MinHeight="50">
    <igDock:ContentPane.Resources>
        <local:NinjectDataProvider  
        x:Key="ViewModel" 
        ObjectType="{x:Type local:SlaTodayViewModel}" 
        />
    </igDock:ContentPane.Resources>
    <igDP:XamDataGrid DataContext="{StaticResource ViewModel}" DataSource="{Binding Calls}" Theme="Office2k7Black" >

    </igDP:XamDataGrid>
</igDock:ContentPane>

As you can see, the only difference is highlighted above and shows the custom in action.

image  You can see from the image above that the designer capability is not affected with this actually loading from the database, nice!

So, what do we need to do to achieve this marvellous result. its actialy fairly simple, I got out my trusty and found that there is really only one method to override.

Imports System.ComponentModel
Imports System.Threading

Public Class NinjectDataProvider
    Inherits DataSourceProvider

    Private m_objectType As Type

    Public Property ObjectType() As Type
        Get
            Return Me.m_objectType
        End Get
        Set(ByVal value As Type)
            If Not m_objectType Is value Then
                m_objectType = value
                Me.OnPropertyChanged("ObjectType")
                If Not MyBase.IsRefreshDeferred Then
                    MyBase.Refresh()
                End If
            End If
        End Set
    End Property

    Private Overloads Sub OnPropertyChanged(ByVal propertyName As String)
        MyBase.OnPropertyChanged(New PropertyChangedEventArgs(propertyName))
    End Sub

    Protected Overrides Sub BeginQuery()
        If m_objectType Is Nothing Then
            Me.OnQueryFinished(Nothing, New InvalidOperationException("You must provide an ObjectType"), Nothing, Nothing)
        End If
        Dim result As Object
        Try
            result = Application.NinjectKernel.Get(m_objectType)
            Me.OnQueryFinished(result, Nothing, Nothing, Nothing)
        Catch ex As Exception
            Me.OnQueryFinished(Nothing, ex, Nothing, Nothing)
        End Try
    End Sub

End Class

I do not yet need all the fancy features of yet so I have only implemented the bit that I need at the moment. If I am adding more (and get it working) I will blog about it in the future.

To get this working I needed to add an instance of an IKernel object to the “Application” file so I have a single Kernel instance through my application unless I want another, but this is a small price to pay and it could well have been done in the same way as the My.Unity.Resolve(Of Ninja) post I did on .

Start your Ninja training today!

 

<iframe src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&Task=Get&PageID=31016&SiteID=1" width=1 height=1 Marginwidth=0 Marginheight=0 Hspace=0 Vspace=0 Frameborder=0 Scrolling=No> <script language='javascript1.1' src="http://ads.geekswithblogs.net/a.aspx?ZoneID=5&Task=Get&Browser=NETSCAPE4&NoCache=True&PageID=31016&SiteID=1"></script> <noscript> </noscript> </iframe>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Martin Hinshelwood

Instructor / Trainer
Northwest Cadence
United States United States

Member

Follow on Twitter Follow on Twitter

Martin Hinshelwood is an Senior ALM Consultant at Northwest Cadence, but also a Microsoft Visual Studio ALM MVPs in Washington, US (Formally UK) and has over 9 years experience in the software industry. He is a member of the Visual Studio ALM Rangers and is also a Professional Scrum Trainer. He regularly writes on his Processes, Practices & Tools blog, and speaks often on Scrum, good practices and Visual Studio ALM.

 

Martin aims to provide Strategic and Tactical consulting on successful implementations of new Processes, Practices & Tools within both small and large organisations across the world. These would include, but not be limited to:

 
  • Scrum Mentoring & Training - Scrum Master Training, Scrum Developer Training, Scrum Mentoring, Scrum Coaching
  •  
  • Practice improvements – Requirements (Backlog,Limiting Work In Progress, Relative Complexity, Acceptance Criteria, Planning Poker, User Stories, Use Cases, Visualisation) , Teams (Team Protection, Commitment), Code (Unit Testing, Branching, Continuous Integration, TDD, ), Test (Acceptance Test Driven Development, Automation, ), Release & Configuration (Continuous Delivery, Continuous Deployment)
  •  
  • Visual Studio ALM Implementation, upgrades & Training - Visual Studio, Team Foundation Server, Team Foundation Build & Microsoft Test Manager


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Mobile
Web02 | 2.5.120517.1 | Last Updated 31 Aug 2009
Article Copyright 2009 by Martin Hinshelwood
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid