Friday, June 6, 2014

A simple modular design for jQuery-based single page application (SPA)

Due to the complexity of a single page application, there are separate JavaScript files for different functions of a page. We developed a simple JavaScript modular system to organize these files. A typical module is an assignment of an IIFE (Immediately-Invoked Function Expression) to a global variable. It has the following structure:
var globalName = (function($) {
    // declarations of variables and functions
var declaredName1 = …;
var initModule = function(dep1, dep2) {
    // Initialization code using dependent module or dependent module variables
    …
};
var onDocumentReady =  function () {
   // code to be executed in JQuery on document ready call
   …
};
return {
    name1: declaredName1,
    …,
    initModule: initModule,
    onDocumentReady: onDocumentReady
};
} (jQuery));
The above code executes when the JavaScript file is loaded into an HTML page. The result of its execution is an assignment of an object with some exported names to a global variable. Each module only has one global name.

Each HTML page also has a pageRun.js that initialize each module and call a module’s onDocumentReady() function. It has the following structure:
jQuery(function() {
globalName.initModule(dependent1, dependent2);
globalName. onDocumentReady();
});
In the above code, shared modules and independent module run first. A module should be initialized and run after its dependent modules. The initModule() call makes the dependent relationship explicit. 

Thursday, June 5, 2014

Include StyleCop in build process

The following are steps to include StyleCop in build process. It  is based on: http://stylecop.codeplex.com/wikipage?title=Setting%20Up%20StyleCop%20MSBuild%20Integration&referringTitle=Documentation

You may want to change the 4.7 with the StyleCop version used in your project. 

1. Download StyleCop
2. Copy the StyleCop binary {Program Files}\StyleCop4.7 to the repository solution folder:  {Solution Folder}\ExternalTools\StyleCop\V4.7. Solution folder is where the VS solution file located. 
3. Copy all of the files from {Program Files}\MSBuild\StyleCop to the {Solution Folder}\ExternalTools\StyleCop\V4.7 folder. 
4. Edit {Solution Folder}\ExternalTools\StyleCop\V4.7\StyleCop.targets to make it to use the copied binary files in the same directory:  <UsingTask AssemblyFile="StyleCop.dll" TaskName="StyleCopTask"/>
5. Put Settings.StyleCop in the {Solution Folder} to set solution-wide StyleCop rules.

The above steps are for the whole solution, for each project, you need complete the following steps. 
6. Add one property definition in the project file <PropertyGroup>:  <StyleCopTargets>..\ExternalTools\StyleCop\v4.7\StyleCop.targets</StyleCopTargets>
7. In the same project file, add the <Import Project="$(StyleCopTargets)" /> after <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
8. In the Debug <PropertyGroup>,  set run code analysis to true:  <RunCodeAnalysis>true</RunCodeAnalysis>

Friday, April 18, 2014

ASP.NET application pool, worker process, app domain and thread

This is my answer to a stackoverflow question:

One IIS server may have multiple application pools.
One web application binds to one application pool.
One application pool may have more than one worker process (when Web Garden is enable).
On worker process can have multiple app domains. One app domain lives only in one worker process.
One app domain may have multiple threads. One thread can be shared by different app domains in different time.

The meaning to ASP.NET developers: to make your web site scalable, don't use in-proc session and don't use static class variable lock for synchronization.

Upsert : Update a row if it exists else insert a new row

Some applications need an "upsert" operation: update a row if it exists else insert a new row. The following is a summary of solutions I found online. 

Suppose we have the following table in a SQL Server database that is mapped to a C# class using Entity Framework. 

CREATE TABLE dbo.Foo
(
ID int NOT NULL CONSTRAINT PK_Foo PRIMARY KEY,
Bar int NOT NULL
);
GO

The following C# code is a naive implementation of the upsert logic: 

int id =3; 
int bar = 199;
Foo foo = this.dbContext.Foos.find(id);
if (foo == null) 
{
foo = new Foo 

ID = id,
Bar = bar
};

this.dbContext.Foos.Add(foo);

else 
{
foo.Bar = bar;
}


this.dbContext.SaveChanges();

The above code doesn't work correctly when multiple users run the same code simultaneously. A duplicated key error happens when more than one users  try to insert different rows with the same key value.  A possible solution is to catch the duplication key error and try the above operation again. The benefit is that we handle everything in C# code. The disadvantage is the added complexity because of the error handling and try logic. As described below, it has race conditions that don't work correctly for non-idempotent update. 

Adding C# synchronization such as a lock in a static class variable helps. However, the solution breaks when web garden is enabled in the hosting ASP.NET application pool. Each worker process has its own copy of a static class variable. To solve the problem, one needs to use named mutex to enable inter-processes synchronization. The named mutex solution fails when we run multiple Web applications in different server. Another cons is that  the above C# code requires two round trips to the back end database. 

The right solution is to move the upsert operation to the back end database engine and add appropriate database locks. The tricky thing is to find the right "locks". Though work correctly, using a table level exclusive lock hurts performance. This Conditional INSERT/UPDATE blog gives a good solution:  

CREATE PROCEDURE dbo.Insert_Or_Update_Foo
      @ID int,
      @Bar int
AS

SET NOCOUNT, XACT_ABORT ON

BEGIN TRAN

IF EXISTS(SELECT * FROM dbo.Foo WITH (UPDLOCK, HOLDLOCK) WHERE ID = @ID)
  BEGIN
      UPDATE dbo.Foo
      SET bar = @bar
      WHERE ID = @ID
END
ELSE
BEGIN
      INSERT INTO dbo.Foo (ID, Bar)
      VALUES (@ID, @Bar)
END

COMMIT

RETURN @@ERROR

The key point in the above solution is setting the UPDLOCK and HOLDLOCK locks to avoid race conditions. At any time, only one instance of the stored procedure is allowed to run. The blog author also describes another solution using the SQL merge command:

CREATE PROCEDURE dbo.Merge_Foo
     @ID int,
     @Bar int
AS 
SET NOCOUNT, XACT_ABORT ON;  
 
MERGE dbo.Foo WITH (HOLDLOCK) AS f
USING (SELECT @ID AS ID, @Bar AS Bar) AS new_foo
ON f.ID = new_foo.ID
WHEN MATCHED THEN
UPDATE SET f.Bar = new_foo.Bar
WHEN NOT MATCHED THEN
INSERT (ID, Bar)
VALUES (new_foo.ID, new_foo.Bar);

RETURN @@ERROR;

GO

My original solution was to use a similar merge command but didn't set the HOLDLOCK option. As the blog author pointed out: without HOLDLOCK, the merge command releases its UPDLOCK after the existence checking and opens the door for multiple concurrent inserts. 

Another possible solution that doesn't use an explicit lock is to insert first, check error code for duplicated key error and update in the second step.

BEGIN TRY
 INSERT INTO dbo.Foo (ID, Bar) VALUES (@ID, @Bar)
END TRY
BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE dbo.Foo  SET bar = @bar  WHERE ID = @ID
END CATCH

This stackoverflow  answer discussed this solution and its potential performance issues of error catching. Except the first insert, all following updates incur the expense of error catching. This solution only works in a write-once-read-many situation that has very few updates. If there are many update operations, it is better to do an extra update first. 

UPDATE dbo.Foo  SET bar = @bar  WHERE ID = @ID
IF @@ROWCOUNT = 0
BEGIN 
    BEGIN TRY
INSERT INTO dbo.Foo (ID, Bar) VALUES (@ID, @Bar)
    END TRY
    BEGIN CATCH
IF ERROR_NUMBER() = 2627
UPDATE dbo.Foo  SET bar = @bar  WHERE ID = @ID
    END CATCH
END    

However, if the update is not an idempotent operation such as the above simple value setting, the above TRY-CATCH solutions (including both T-SQL stored procedure and the C# error handling solution) still have race conditions. For example, if the update is "SET bar = @bar + 1", those solutions don't work correctly. As a general upsert solution, the two stored procedures that use UPDLOCK and HOLDLOCK don't have a race condition and work correctly. 

Tuesday, April 8, 2014

JavaScript note: prototype, [[Protyotype]] and prototype property

JavaScript has two types of objects: function object and non-function object. Conceptually, all objects have a prototype (NOT A PROTOTYPE PROPERTY). Internally, JavaScript names an object's prototype as [[Prototype]].
There are two approaches to get any object (including non-function object)'s [[prototype]]: theObject.getPrototypeOf() method and the __proto__ property. The __proto__ property is supported by many browsers and Node.js. It is to be standardized in ECMAScript 6.
Only a function (a callable) object has the prototype property. This prototype property is a regular property that has no direct relationship with the function's own [[prototype]]. When used as a constructor ( after the new operator), the function's prototype property will be assigned to the [[Prototype]] of a newly created object. In a non-function object, the prototype property is undefined . For example,
var objectOne = {x: 5}, objectTwo = Object.create({y: 6});
Both objectOne and objectTwo are non-function objects therefore they don't have a prototype property

Thursday, April 3, 2014

A better way to structure a .net solution

Being able to quickly navigate source files in a large .net solution that has many projects is highly desirable for a programmer. My experience with some projects such as nopCommerce (http://www.nopcommerce.com/) was not a good one. Often it took me two or three tries to the right project folder for a namespace.

This YoutTube video  made by Roger Harford describes a good idea to structure a .net project. Most of the 15 minutes 47 seconds video discusses the reasons why the Visual Studio default structure is not a good one when when source control and multiple projects are added. For example, we usually don't want to use the same name for a solution and its first project. The method to structure a .net solution is rather simple and is summarized below.

When you create a solution in Visual Studio at the beginning, choose the Installed --> Templates -->Other Project Types --> Visual Studio Solution --> Blank Solution. Then name your solution based on your company and product name: MyCompany.MyProduct. Visual Studio will create a folder and solution files based on the new name. 

The "Blank Solution" template creates an empty solution. You can add to this solution a number of projects that are named after your namespace. For example: MyCompany.MyProduct.Web,   MyCompany.MyProduct.Domain,  and MyCompany.MyProduct.Database are good names for a MVC Web site project. 

When you add more projects and source files,  the above solution structure allows a clear and natural mapping between many file names, folder names and namespaces. Additionally, it is easy to move files and folders around and keep a consistent mapping between a namespace and its files.

Tuesday, March 11, 2014

Mulitple "from" statement in LINQ and a Single Element Sequence example

I like to use multiple "from" statement in my LINQ query for two reasons:
1. It's easy to understand. It maps naturally to a nested loop like the following
   
    foreach(var outerElement in outSequence.Where(t => ...)) 
  {
     // outerElement can be used in the inner query
           foreach(var innerElement in outSequence.Where(t => ...))
    {
        ....
    }
  }

2. It is more flexible than "join" because there is not limit on how you use the outer element in inner query. As shown by the following example. 

Sometimes, you may want to select a single element sequence in LINQ. For example, once I needed to use several from statements and some from statement should return a single element sequence. In LINQ, it is pretty easy with a multiple from query:

from outerElement in outSequence
  .Where(t => ...)
from innnerElement in innerSequence
  .Where(t => ...)
  .DefaultIfEmpty()
  .Take(1);

The second "from" statement returns exactly one element sequence result. In the above example, the number of element of the above query result is the number of element returned from the first query.

Monday, March 10, 2014

Visual Studio NuGet package restore

Visual Studio has two approaches to use package restore: Automatic Package Restore and MSBuild-Integrated package restore.  The 'MSBuild-Integrated Package Restore' restores packages DURING the building process that might cause issues in some scenarios. The 'Automatic Package Restore' is the recommended approach by the NuGet team (http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore).

There are several steps to to make 'Automatic Package Restore' work:
1. In Visual Studio, Tools -> Extensions and Updates,  Upgrade NuGet if there is a newer version (Version 2.7 or later)

2. If you use TFS, in your solution's .nuget folder, remove the NuGet.exe and NuGet.targes files. Then edit NuGet.Config to not check in NuGet packages:

<configuration>
    <solution>
        <add key="disableSourceControlIntegration" value="true" />
    </solution>
</configuration>

If you checked in packages folder to TFS, delete the folder and check in the deletion of package folder deletion.

If you don't use TFS, delete the .nuget folder.

3. In each project file (.csproj or .vbproj) in your solution, remove the <Import Project> that references NuGet.targets file. The reference looks like this:

<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />

Remove this line in every project file in your solution.

4. In Visual Studio menu, either through

Tools -> Options -> Package Manager -> General  or
Tools -> NuGet Package Manager -> Package Manager Settings

 please enable the following two options
1) 'Allow NuGet to download missing packages'
2) 'Automatically check for missing packages during build in Visual Studio'

5. Test your package restore configuration by the following steps
1) Save your solution and close Visual Studio
2) Delete your solution's packages folder
3) Start Visual Studio, open your solution and rebuild it.

Tuesday, March 4, 2014

In LINQ to Entities, the Include() method does not work with the Join() method

In using Entity Framework, we try to write queries that only incur one database roundtrip.  However, as described in this blog (http://blogs.msdn.com/b/alexj/archive/2009/06/02/tip-22-how-to-make-include-really-include.aspx), when you introduce an intermediary join or something that change the “shape” of the query, the Include() method will throw a runtime exception stating “method cannot be translated into a store expression”. 

The DbExtensions.Include extension method requires IQueryable<T> where T is the entity type that the Include() method is applied. However, when a join operator is used to join multiple tables, the ‘shape’, i.e., the query result, is changed to a new entity type. The Include() method call fails with this new query result type.

There are two workarounds proposed by the above blog and a stackoverflow.com answer by the same author (http://stackoverflow.com/questions/794283/linq-to-entities-include-method-not-loading).
The first workaround has the following code sample:
var results = 
    ((from post in dbContext.Posts
     from author in dbContext.Authors
         where author == post.Author 
and author.email="abc@email.com"
     select post) as ObjectQuery<Post>).Include(“Comments”);
It requires the final select be an entity that keeps the same query shape to use the Include() method. It only works for a few simple queries.

The second workaround has the following code sample:
var results =
    
from post in dbContext.Posts
    from author in dbContext.Authors
         where author == post.Author 
and author.email="abc@email.com"
    select new { Post = post, Dummy = post.Comments };

The key is to put Dummy = post.Comments in the select clause. The "Dummy" property uses an Entity Framework featured called relationship fixup to populate the entity Properties. This is an elegant solution that works well. The blogger, Alex, explains the fixup in his EF Tips blog (http://blogs.msdn.com/b/alexj/archive/2009/02/25/tip-1-sorting-relationships-in-entity-framework.aspx ):  “In the Entity Framework Object Services automatically ties things together that are related in a process called Fix-up.  Fix-up generally occurs once the second of two related entities enter the context.”

The author (Alex D James)’s LINQ tips blog (http://blogs.msdn.com/b/alexj/archive/2009/03/26/index-of-tips.aspx) has many gems. 

.less (Dot Less), bootstrap 3 and font awesome in Asp.Net: configuration and workflow

Dot-less (www.dotlesscss.org), dot-less is a port of the popular LESS JavaScript library (lesscss.org) for the .NET platform.  It allows variables and mixins to define CSS styles in a more productive way.  The bootstrap (getbootstrap.com) is a flexible front end style framework based on LESS. Though there are many benefits of using bootstrap as the front end CSS framework to build a Web application, the CSS-based approach of using bootstrap requires one to write many bootstrap CSS classes in HTML. It is both ugly and not efficient for a big project and long term maintenance. Ideally we want to use bootstrap without mixing style formats and HTML code. This leads to use a LESS-only method to define all CSS styles in a Web application.
This article covers two subjects. First, we setup an ASP.NET project to use dotLess and configure it to work properly in both debug and release version. Then we define the workflow steps.

1.      Install and configure dotLess package

The following steps are based on Dino Esposito’s MSDN magazine article in http://msdn.microsoft.com/en-us/magazine/dn463774.aspx
1)      Use NuGet to install the latest DotLess package
PM> Install-Package dotLess
2)      Then add a new HttpHandler to Web.Config to support debug mode CSS file request from its LESS code.   There are two places: one for classic mode (IIS 6.0 or below) and one for integrated mdoe (IIS 7.0 and above)
<system.web><httpHandlers>
   <add path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler, dotless.Core" />
</httpHandlers></system.web>

<system.webServer><handlers>
  <
add name="dotless" path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" />
</
handlers></system.webServer>
Optionally, we can specify a configuration section for the LESS/CSS request.
<configSections>
  <
section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core" />
</
configSections>
<dotless minifyCss="false" cache="true" web="false" />

3)      We need to configure bundling and minification
First, we need to use NuGet to install a LESS bundle transformer. A simple transformer described in the above MSDN article doesn’t understand file path. The System.Web.Optimization.Less package is what we want.
Then add all your less files to a bundle in your BundleConfig.cs
bundles.Add(new LessBundle("~/Content/Less").IncludeDirectory("~/Content/Less", "*.less"));
Finally, use the generated CSS file in your code Razor view file
@Styles.Render("~/Content/Less")

2.      The workflow

The bootstrap style workflow is based on the general bootstrap 3 less workflow tutorial described by Erik Flowers in his blog: http://www.helloerik.com/bootstrap-3-less-workflow-tutorial.
We put all less files in ~/Content/Less folder. There are two sub folders: one is bootstrap and another one is local. The bootstrap folder has all the LESS files downloaded from bootstrap packages. We also need a ~/Content/fonts folder to store all fonts used by bootstrap fonts. Copy all bootstrap font files to this folder.
Then define our variables, mixins and page-specific LESS files in the local folder.
Finally, use a Style.less file to import all used LESS files in the ~/Content/Less folder.

To use font-awesome, we need to create a font-awesome folder in ~/Content/Less folder and copy all font-awesome LESS files to the folder. Then copy all its fonts to the ~/Content/fonts folder. We need to change its font path to
@fa-font-path:        "../../fonts";
To make the body use auto width and keep the bootstrap .container style, add the following styles instead of .container;
.container-fixed();

Friday, February 28, 2014

tinymce editor in dynamical content inside bootstrap modal dialog

I need to use tinymce (http://www.tinymce.com/) editor in dynamically crated content inside bootstrap modal dialogue. The official document doesn't help and my online search found few tips. After a few tries, following are key steps to use tinymce in dynamic content:

First, we need to make the focus in event work properly inside bootstrap dialog  (http://www.tinymce.com/wiki.php/Tutorials:TinyMCE_in_a_boostrap_dialog)

// Prevent bootstrap dialog from blocking focusin
$(document).on('focusin', function(e) {
    if ($(e.target).closest(".mce-window").length) {
        e.stopImmediatePropagation();
    }
});

Second, after the modal dialog statement, initialize tinymce.

$('#myDialogElement').modal();
$('#myTextArea').tinymce( { width: '100%', menubar: false});

Third, remove the tinymce editor when the modal dialog closes, as the first step, this is called in jQuery initialization.

$('#myDialogElement')on('hidden.bs.modal', function (e) {
        // need to remove the editor to make it work the next time
        tinymce.remove();
});

In the above code, we NuGet the jQuery version tinymce. Both jquery.tinymce.min.js and tinymce.js are included in the Web page.

Monday, February 24, 2014

A fluid responsive grid layout in Bootstrap 3

Unlike Boostrap 2, Bootstrap 3 doesn't have a .container-fluid mixin to make a fluid container. The .container is a fixed width responsive grid layout. In a large screen, there are excessive white spaces in both sides of one's Web page content.

A fluid grid layout uses all screen width and works better in large screen. It turns out that it is easy to create a fluid grid layout using Bootstrap 3 mixins. The following line makes a fluid responsive grid layout:

.container-fixed;

The .container-fixed mixin sets the content to the center of the screen and add paddings. It doesn't specifies a fixed page width.

Another approach is to use Eric Flowers' CSS style (http://www.helloerik.com/bootstrap-3-grid-introduction)

.my-fluid-container {
  padding-left: 15px;
  padding-right: 15px;
  margin-left: auto;
  margin-right: auto;
}

Wednesday, January 22, 2014

Using SignalR in an Asp.Net MVC 5 project: basic setup and Unity integration

This article covers the basic setup and Unity integration of using SignalR in a MVC project.

1.    Basic Setup

There are three steps in using SignalR in MVC:
·         Adding SignalR library;
·         creating OWIN startup classes to setup SignalR route;
·         writing server side and client side code.

First you need to use NuGet to install Microsoft.AspNet.SignalR package.
install-package Microsoft.AspNet.SignalR
This will install both server side packages and client side JavaScript libraries into your MVC project.
Then you need to configure SignalR routes in application startup. Create a C# class file (the filename and location doesn’t matter but a recommended one is “SignalRStartup.cs” in App_Start folder) with the following content (code snippets are copied or modified from examples in http://www.asp.net/signalr/overview/signalr-20/getting-started-with-signalr-20/tutorial-getting-started-with-signalr-20):
using Microsoft.Owin;
using Owin;
[assembly: OwinStartup(typeof(MyNamespace.SignalRStartup))]
namespace MyNamespace
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();
        }
    }
}

In the server side, you need to create a Hub subclass in your controller folder. A sample is
using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
    public class ChatHub : Hub
    {
        public void Send(string message)
        {
            // Call the broadcastMessage method to update clients.
            Clients.Others.broadcastMessage(message);
        }
    }
}

In your Web application, the View file should include "~/Scripts/jquery-{version}.js",,"~/Scripts/jquery.signalR-{version}.js" and "~/signalr/hubs".
In the client side, you need to call the server side method as well as define a method to be called by Server side method.  The code may look like the following:
var chat = $.connection.chatHub;
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
        chat.server.send('Hello World');
    });
});
 
chat.client.broadcastMessage = function (message) {
    alert(message);
};

The JavaScript code use camel-cased version of the server method name.  The generated signalR proxy automatically convert a method name to a correct one. In the server side, there is no method name conversion. A server calls the camel-cased JavaScript client method.

2.    Working with Unity IoC container


After using NuGet to install Unity and Asp.Net SingalR packages, one needs to perform the following steps to resolve types for SignalR methods using a Unity container. There are two options to use Unity as dependency resolve in SignalR: one is to replace the whole SignalR dependency resolver; the other option is to only replace the IHubActivator component of the SignalR dependency resolve. The first one is document in http://www.asp.net/signalr/overview/signalr-20/extensibility/dependency-injection. It needs to implement two methods (GetService and GetServices) of SingalR IDependcyResolver interface. The second option only needs to implement one method of SingalR IHubActivator interface.

Not only the first option has more methods to be implemented, but also it needs future steps to allow type resolve in Hub classes. Therefore we choose to use the second option. The following steps are based on http://damienbod.wordpress.com/2013/11/05/using-signalr-with-unity/.
First, create a class implementing IHubActivator interface. In the class, use a Unity container in the IHub Create(HubDescriptor descriptor) method.

using System;
using Microsoft.AspNet.SignalR.Hubs;
using Microsoft.Practices.Unity;
 
namespace SignalRHostWithUnity.Unity
{
    public class UnityHubActivator : IHubActivator
    {
        private readonly IUnityContainer container;
 
        public UnityHubActivator(IUnityContainer container)
        {
            this.container = container;
        }
 
        public IHub Create(HubDescriptor descriptor)
        {
            if (descriptor == null)
            {
                throw new ArgumentNullException("descriptor");
            }
 
            if (descriptor.HubType == null)
            {
                return null;
            }
 
            object hub = this.container.Resolve(descriptor.HubType) ?? Activator.CreateInstance(descriptor.HubType);
            return hub as IHub;
        }
    }
}

Next, set SingalR Hub resolver in the Unity configuration file.  There is no need to register IHubActivator in Unity as described in the above reference because this interface is only used by SignalR and should be registered only in the SignalR dependency resolver.  
var container = new UnityContainer();
GlobalHost.DependencyResolver.Register(

    typeof(IHubActivator), 

    () => new UnityHubActivator(container));

Finally, register every application Hub class in the Unity configuration file.
container.RegisterType<MyHub, MyHub>(new TransientLifetimeManager());

Together, the Unity configuration file looks like below:
var container = new UnityContainer();
container.RegisterType<MyHub, MyHub>(new TransientLifetimeManager());
 
… // register other types
 
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
 
GlobalHost.DependencyResolver.Register(

    typeof(IHubActivator), 

    () => new UnityHubActivator(container));