Dependency Injection in ASP.NET vNext (adding Unity container)

by BillKrat 24. August 2015 06:26

As a prerequisite to reading this blog I would strongly suggest you review the “.NET Web Development and Tools” blog on this topic at Dependency Injection in ASP.NET vNext.

We live in an agile world which gives us the opportunity to work with the latest and greatest as it unfolds.   As such I found the above link helpful, but not complete as the latest videos on this topic (as of this writing) suggest that we have to return our IServiceProvider implementation from ConfigureServices – which is by default a void method.   In addition to videos I found the blog on using Autofac IOC container that provided more clues, but still fell short….

My research found that it will be the DI container authors responsibilities to make the necessary adapters for their respective containers (as Autofac did).  If you are like me and don’t want to be blocked, nor code in a lot of technical debt until the DI container vendor creates their service provider adapter for ASP.NET MVC, I offer a “poor man” adapter that will get the job done so that you can code against your favorite DI container.

The shortfall eluded to above was that the ASP.NET MVC 6 template had a lot of code in it and simply returning my Unity Service Provider was a more daunting task (reference method in image below).   A task that required me to dig into the source code to figure out how to create and implement my own provider.

SOURCE CODE: contains two classes and an interface in => 
                          (project has dependencies DependencyInjection beta 6)

BUG: There is a bug in MVC beta 6 that causes the default provider to be returned even if a new/different
         implementation is  returned by ConfigureServices.  Reported here with work-around

The following Startup code shows the updated source for my POC highlighted in a yellow box.   I should note that without line 98 my HomeController (which has dependency property requiring setter injection by Unity) will never be seen by the IServiceProvider implementation – the controller will be “new’d” up versus resolved.

The code comments will make the remaining code self explanatory – I’ll just add that the UnityContainerManager wires up the UnityServiceProvider (these two classes are all that are required).


I take a rather simplified approach that allows the developer to use both the default IOC container while providing their own (has less moving parts and places for failure).  When you review the UnityServiceProvider class code you’ll find that I first try to resolve types using the default MVC service provider and if successful return its value, IF NOT SUCCESSFUL I’ll use the Unity Container to resolve the type – this works because I have no plans or intentions of modifying Microsoft code (even though it is open source) to where I’ll need to inject my components into them.   If I require any default framework implementation, i.e., logging, then I’ll inject an instance into my container when I register other implementation (reference line 113 above).

The “cool” part of this process was that I would need to change the default return value of ConfigureServices from “void” to “IServiceProvider” and it would know how to use my provider.   I connected to the source code, put a break point at the end of CreateServices and when I stepped out the calling process gave me the information I needed; BuildServiceProvider (line 106 above).   On line 41 below, if CreateServices is void it will return null resulting in a default service provider being constructed using BuildServiceProvider, otherwise it returns the provided instance – so whether void or not it returns an instance of IServiceProvider.


Note the blue highlighted line in above image (bottom Locals pane): if I had not taken the simplified approach of using both default and Unity service providers I would be responsible for transferring the 241 interface, scope, and implementations into my container. 

To simplify code I decided to register my Unity container manager with the “default” service provider (line 103 below), build the Service Provider for default services (line 106), and then resolve my IUnityContainerManager implementation on line 110. 


I did this to save some coding steps, this effectively allows me to grab an instance of the default MVC service provider via constructor injection in my UnityContainerManager (reference below line 30).   Note on line 43 that I effectively store the default service provider in “my” Unity container with a named parameter so that I can retrieve it in my UnityServiceProvider.


This keeps my Unity service provider compact and lightweight as shown below.  On lines 23-30 I attempt to resolve the type using the built-in (default) service provider (which in my POC has 241 registrations).  If the value is not null then I use the Unity container’s BuildUp method so that any dependency properties will be injected (setter injection); this is required for Controllers setter injection.  If null is returned I then use my Unity container (line 46) to resolve the type.  

IMPORTANT NOTE: Controller constructor injection will utilize the ASP.NET MVC default service provider – not the Unity service provider.  After the default service provider resolves the controller (line 30 below) the Unity Container will perform a BuildUp (line 39) effectively setting any dependency properties registered in the Unity container.  


Below is the final result of my POC


How to use SQLite Designer Support in Visual Studio (5 steps)

by BillKrat 29. June 2015 21:02

The SQLite.NET.chm available HERE states the following:

Installing SQLite Visual Studio Design-Time Support

Supporting the Visual Studio query designer and allowing you to manipulate SQLite databases from within Visual Studio is a great time-saver.  Though the support is not yet fully-implemented, there's certainly enough there to keep you busy.  You can create databases, design and execute queries, create typed datasets and lots more all from Visual Studio.

Installation Instructions

Download and run one of the setup packages and then select the "Install the designer components for Visual Studio 20XX." option when prompted.

Which is all very promising but left me with a wee bit of a headache working out the details – I’ll share this adventure here to hopefully make it easier for the next person.

1. Go to THIS LINK and find the setup package that applies to your version of Visual Studio – note that the x64 does not install the design-time components, only the x86 version does.  Since I am using NuGet to install the libraries I’ll use this package primarily to install the design-time components.


2. Once you download the application, right click on it and run as administrator – when you see the following screen ensure the “Install the designer components for Visual Studio 2013” is checked.


3. There will be no apparent changes in Visual Studio however if click on View and open the Server Explorer you can select System.Data.SQLite Database File as the Data source.


4. Click on Continue which will open the “Add Connection” window.  Type in the full path of your database, which will be in the bin\debug folder of your project (assuming desktop application in DEBUG environment).  Click Test Connection to see if your connection is successful.


5. Use the designer as applicable to update your database.


SQLite Primer for .NET and Visual Studio installation (9 easy steps)

by BillKrat 29. June 2015 19:10

I guess when something is easy to use much is assumed – setting up Sqlite to work with my Visual Studio projects took longer than it should have – it is amazing how little documentation there is on the topic…

The first step I generally take is to install from NuGet

1. Right click on Project References
2. Click Manage NuGet Packages…
3. Search for SQLite
4. Select System.Data.SQLite (x86/x64)
5. Click the install button (it will install all dependencies)

In this case I was not disappointed to find SQLite available, what was more promising was the ADO.NET provider.  My initial efforts to install it in my Universal Apps did not yield expected results so I opted to go from the known to the unknown – I’ll start with Test Driven Development (TDD) on the desktop platform.


Now that it was installed I wanted to see it work.  I accessed the System.Data.SQLite home page and was disappointed to find nothing available online, but the link to the SQLite.NET.chm was hopeful. 

6. I download the document and found some code under the “Introduction to System.Data.SQLite” in the “Using DbProviderFactories” section – I grabbed the code from Scenario 2 and plugged it into my unit test.


Well that would have been too easy…  What would have been nice is a reminder (it has been a long time since I dabbled in ADO.NET) that you have to:

7. Right click on project References
8. Add a reference to System.Data (knowledge assumed)

This made the IDE happy as all of the red went away, but it did raise a question in my mind as to how I was going to run this code in the Universal App world as it won’t have access to System.Data (an adventure for another day). 

So I run my unit test and walla!   Not an expected result….  (knowledge assumed)


9. Copy the code from the documentation referenced in step 6 (Scenario 1) into the App.Config file. 

Note that the NuGet installation added an invariant for EF6 (Entity Framework 6 lines 10-13 in bottom pane of image below) but not for the code the documentation references.  This makes sense as I can now assume that GetFactory (line 16 in top pane of image below) will retrieve the configuration information for “System.Data.SQLite” which I just pasted into it (bottom pane).


Walla!  I now have successfully opened my database and can start TDD on the data access layer.

There is plenty of documentation out there for ADO.NET and the referenced documentation that I download has a section on ‘Query Language Understood By SQLite” so I trust my adventures should be less challenging…


Xamarin – If I build it, will it run?

by BillKrat 8. March 2015 18:29

I may not know until the end of the year…. as I shared in my blog “Xamarin – from a seasoned Visual Studio developers perspective” without a ROI Xamarin won’t be on the budget until the end of the year.  However, this doesn’t mean that I can’t continue to create a framework that will be supported by Xamarin.  The way I plan to do this is to use an Xamarin Portable Class Library (PCL) in my Visual Studio project (ref figure 2) and put all of my shared code in it.

SOURCE CODE: Change set 107213

Xamarin Studio isn’t going to make it easy for me though, ideally it would be great if I could reference the MvpVmXamarinPcl project, create a Bootstrapper class in the TaskyAndroid project (more on this below), and watch it work with some basic functionality.   But this won’t be the case, as soon as a project references a PCL in Xamarin Studio – your greeted with a message that states it is not supported in the Starter edition.
So this leaves me with only one recourse – don’t make a reference to the PCL and periodically build the Xamarin solution to ensure it at least builds as I use/share it in my Visual Studio solution.  


Figure 1

I am very pleased to see that Xamarin supports Microsoft Unity IOC and MVVM Light!  This adventure went far smoother than I thought it would, particularly after the last adventure referred to in above blog link.

So I created a MvpVmXamarinPcl project in Xamarin Studio (it is a Portable Class Library, aka PCL) and added it to my Visual Studio solution for my open source password manager.  I then did the following:

  • Ported all of the code out of the existing Visual Studio PCL into the new MvpVmXamarinPcl
  • Used NuGet to install the MVVM Light and Unity packages
  • Deleted the now legacy VS PCL
  • Changed all my references to use the new Xamarin PCL project

and was pleasantly surprised to find everything compiled and the application successfully ran in Visual Studio using this Xamarin generated PCL project! 

What code am I placing in this Xamarin PCL?  An IOC framework, with event aggregation and classes emulating Prism libraries (reference image below); developers with Prism experience will feel right at home with this framework.   Thanks to MVVM Light I don’t have to worry about creating the XAML binding components.  Below in the left bottom corner of figure 2 I show the application running (with 5 modules).

Figure 2

Note: the only class from the above sequence diagram that is not within the framework PCL is the Bootstrapper class which resides in the primary application project.

The Bootstrapper (top left corner of image below) is responsible for loading the modules for the application.  In this case the modules reside in a separate MvpVmDesktop project (middle pane of figure below), each platform project will house its own UI components, for now I will be working on the Windows Desktop.

Currently, all of the modules are identical to the Menu Module in that there is only barebones code and each respective View (bottom left corner of image below) is data-bound to the same MainViewModel

Figure 3

As demonstrated below the only class from this point forward that will do any work (have code) is the Presenter, e.g., MenuBarPresenter (middle right pane of image above); neither the View or ViewModel will have any code that is not related to UI.  This is an important feature of MVP particularly for an environment such as this where each platform will have UI specific code sharing external logic; for the most part the MvpVmDesktop project will have only UI specific code, as will the MvpVmPhone, and later Android and IOS projects.


Xamarin – from a seasoned Visual Studio developers perspective

by BillKrat 1. March 2015 05:04

The minute my daughter was born I realized that TV sold a lot of hype on how babies look when they first come out; I stood there as a young 20 year old with my jaw dropped; she was all purple, yucky looking, and my first reaction was “put her back! she isn’t done yet”.  Well it turns out she was done and grew up to be a beautiful young girl and lady – so perhaps that is the moral to this story?
Day one with Xamarin was a wasted day of my life, I’m putting it back because it doesn’t feel like it is done yet, I’ll try again at the end of the year.   Perhaps I should have waited longer?  In my last correspondence with them a little over a week ago they indicated that in a couple of months they will release a “starter” edition that includes Visual Studio integration, but I should “dabble” in the current version until then.    This was in response to my request to have a version (like Microsoft Visual Studio) that would allow a developer to learn how to use their system without having to spend $900.00 up front (only Xamarin business edition supports Visual Studio integration); I indicated to them that there is no return on investment (ROI) and it is not in my budget.

A prerequisite for any Microsoft Visual Studio developer that wants to start dabbling in Xamarin is Jim Wilson’s webinar on “making cross-platform mobile apps with Xamarin and C#”.   This webcast goes a long way to answer a lot of questions that I had coming out of the gate in regards to the environment, although I must admit I only made it half way through because I was anxious to get started and my SamSung slate just reported a successful install of Xamarin.

The adventure follows:

My first mistake was downloading the following two applications off of the main page:


This is what kicked off most of my days efforts – I didn’t have an emulator so I couldn’t run anything.  


This adventure assumed a lot of knowledge on the part of the Microsoft developer, you have to know how to add an emulator.  When I first went into the Google Emulator Manager (from Tools menu) and created one it complained that there was not a CPU/ABI – some Bing research on this revealed that I had to add an image….


This eventually led me to the Android SDK Manager, between it and the Project Options (comparable to Project Properties for Visual Studio projects) I started to tie things together…

Xamarin Projects are tied to API versions on the options | Build | General tab.  The “Tasky” project that I was actually able to load and run in the emulator had two emulators “MonoFor…(API 10)” and “MonoFor…(API 12)” as shown in the bottom right pane of the image below.  In the case of Tasky project it was using Android 2.3 (Gingerbread).

So through a process of elimination I installed the Android 5.0.1 (API 21) images shown below (under status column) which allowed the Emulator to load.  I had to use the process of elimination because I only had 10 gig available on my SamSung slate (64 gig drive) and these images quickly consume gigabytes of drive space – first efforts failed after a very time consuming download process because it filled up my drive.


After hours worth of research, trial, error, and work I didn’t even get to see the emulator run….   I created a new Android 5.0.1 project, set the emulator and as you’ll see below a brand new project exceeds the “free” license size and I have to have indie edition or higher to use it… Indie is affordable but it doesn’t support Visual Studio and you can’t create Windows Phone applications in Xamarin (only VS) – so all of the constraints mean that only the Xamarin “Business” edition is feasible which has a $899 price tag which is not feasible without a ROI.


BUT I WASN’T READY TO GIVE UP – I wanted to see how it worked so I started browsing the code, I was curious how MVVM worked in this framework.   I started with the Login screen which had a ViewModel in a different project, I quickly saw that it uses the MVC/MVP Passive View pattern (see How it Works) in that the controller, LoginActivity class, is responsible for updating the view model; the view is not using the Observer Pattern (data binding).

I thought perhaps this would be different with a XAML view but when I added one the compiler complained and by this time I was done chasing issues so I simply deleted the XAML page.   BTW, it took me a long time to figure out that the Views are stored in the Resources\Layout folder with the code-behind (for a lack of a better word) residing in the root of the project.


BUT I STILL WASN’T READY TO GIVE UP, I wanted to see something run…  As I eluded to above I was able to load and run the Tasky project so I started dabbling with it – in all of its older version limitations….

So I loaded Tasky, was glad to see the emulators, clicked run and 3-1/2 minutes later the emulator was loaded and running the application.   No carpel tunnel problems here, plenty of time to rest/recoup.  I got curious and timed myself getting a cup of coffee from my Kuerig machine, making toast, putting the butter back in the fridge after buttering my toast and getting back to the office – walla!  3-1/2 minutes.  At least I can spend this time productively :)

But I was thinking, I can live with this for the ability to develop multi-platform….  So I loaded the view and was a wee bit disappointed in the available controls and design time experience.  Visual Studio WinForms and XAML really have us spoiled…   So I make a few updates to the screen, learned that I have to use a TableLayout (much like a Grid in XAML) and clicked run on the emulator.  It compiled and then …..


CRASH - the following was the only clue to the problem, the compiler was a happy camper and blindly handed the app off to the emulator.  The emulator didn’t like something….


It was becoming clear that you get what you pay for in the Android/IOS development world.  I trust that experienced developers in these environments would know what to do but as a newbie (experienced Microsoft) developer it is a miserable experience because we are use to having stuff just work.  If I add a project and hit run – it just works, doesn’t matter if it is Windows Phone, Tablet, Desktop, Web, or console.   The emulators rock!!

So I’m sticking a fork in it for now – we’ll see how far things progress.  I trust with Microsoft and Visual Studio in the scene we experienced Microsoft developers should be able to feel more at home and have things just work…

In closing…

You can emulate the development experience if you create a Portable Class Library (PCL) project in Visual Studio (which has no WinForms or XAML support) and put all of your shared code in it (this is all you can share); PCL is a subset of .NET which has less features than Silverlight does. 

The PCL concept is used for Xamarin development in that you create a Portable or Shared library for the code you will use between platforms, but all of your UI logic has to be done in the Android or IOS project (at least for Xamarin Studio).

Xamarin Studio does not support IOS for Windows, you have to use OSX (a Mac), likewise it does not support Windows Phone so it is pretty much useless unless you are doing Android development.

Visual Studio reportedly will support Android, IOS, as well as Windows Phone development, however after installing Xamarin successfully Visual Studio 2015 preview had no clue Xamarin was installed – so I was forced to play in Xamarin Studio.

It was truly an adventure….

I can guess your number in 6 steps (using linear algebra)

by BillKrat 27. February 2015 03:50

I’m taking a linear algebra course and was tasked with an assignment to demonstrate how it can be used to perform a “magic trick”.   The instructor gave a couple of examples which got me thinking – “how can I use it to guess a persons number and reveal it to them”.  The answer follows:



How it works => CLICK HERE



Online 3D model editor and artist website

by BillKrat 24. February 2015 19:12

Source: SculptFab-face.obj  (this is actually a text file)

The above source file can be loaded into SculptFab’s online editor at: 
Note: site worked with FireFox and IE 11.

Sculptfab is a very simple tool letting you sculpt 3D models in the browser and publish them in 1 click to   Tutorial is available at THIS LINK


I created an account at SchetchFab and with a click posted my 3D face to
Note: site worked with FireFox and IE 11.




The type name or alias … could not be resolved. Please check your configuration file and verify this type name

by BillKrat 18. February 2015 08:38

This one took me more time than I care to admit as well as a number of dead-end Bing searches…   There are any number of reasons why Unity won’t load a configuration file, i.e., typo in “type” or “mapto” attributes, but in my case these were correct – I even copy/pasted both namespace and class names to ensure there was not some unforeseen typo.

What I didn’t quickly find was resolution to my issue which was that you must have an <assembly name=”” entry in your configuration file.  Once I added it Unity happily loaded the configuration file.


GhostDocUtil – adding custom pages to your .chm file

by BillKrat 16. February 2015 20:38

            Source: (Visual Studio 2012 and greater)
  Prerequisites: Html Help Workshop  
                           When prompted associate .HHP file with C:\Program Files (x86)\HTML Help Workshop\HHW.EXE
Documentation: GhostDocUtil: Help folder contains a GhostDocUtil.chm file.   See Quick Start for more details

The Ghost Doc application is an amazing tool for documenting source code, I particularly like the preview feature.  The only issue I encountered was that it only generates an API listing, e.g., you’ll only see the area shown in the red box in figure 1. 

I found a way to back door the system so that I could add custom pages which prompted me to write a utility to automate the process.   GhostDoc generates all of the files necessary for the Html Help Workshop to compile a new .chm – thus providing the means to add custom pages.  However, after successful building the .chm it deletes all of the files (more specifically the temporary folder).  So the key was to figure out a way to prevent this from happening at a point when processing was completed.   The solution was to open the .chm after a successful build and then build the help file again, this generates an error message (which I ignore) which opens the door for GhostDocUtil to automagically generate the custom pages.

The entire process takes six manual steps which are outlined in the Quick Start page (see prerequisites above).  The important part is that you can author your custom pages using a normal .htm page as shown in figure 2. 

The GhostDocUtil.chm pages combined with the GhostDocUtil source code (which was used on itself to generate the documentation) should give you the information necessary to create custom pages for your project’s documentation

Figure 1 screenshot of .chm after processing custom pages

Figure 2 solution folder screenshot

GhostDoc solves the age old problem of documentation

by BillKrat 15. February 2015 10:02

See GhostDocUtil for information on how to create custom pages in your .chm.

Historically the problem with technical software documentation has been keeping the UML diagrams and/or documents in sync with the code.  GhostDoc Professional and Enterprise now offers a solution to the problem.

GhostDoc not only provides an easy means to generate XML documentation, it also supports the ability to easily add images and preview documentation.  In figure 2 below I show the UML sequence diagram that represents the business logic flow of the BootstrapperBase class.  In the future, if I am working on this section of code all I would have to do is right click on the code and request a preview (reference figure 1).  It will show me the documentation preview shown in figure 2 (right pane) where a picture will truly say a thousand words – particularly when I reference this diagram from the bootstrapper class that will derive from it.

As for up-keep, all I have to do is keep the XML documentation current as I modify the code and after updating the UML diagram I’ll then then capture a screenshot of it saving it using its use case designator, in this case SD0300-020-075-010.PNG.  Walla!  We’re documented and can move on without looking back; all references to this use case within documentation will be updated when I produce the .chm file.  Likewise it will be current for the next preview.

This provides a great return on investment making it worth the time to clearly document each process in a class. 

I will be using this for my open source project which will utilize my Prism Light framework

Figure 1 right click on code, select GhostDoc Enterprise, and request a preview

Figure 2 code with preview