Dependency Injection (DI) & Registration Madness

I recently saw an application that has many services being registered with a DI container as below.

container.RegisterType<ICustomerSearchService, CustomerSearchService>();
container.RegisterType(typeof(IWriteRepository<>), typeof(WriteRepository<>));
container.RegisterType(typeof(IReadRepositories), typeof(ReadRepositories));

This is just a few but there are 100s of registrations and it is continue to grow…


One of the developers has taken a new approach to split registration across multiple classes. But again there are still loads of type registrations.

This is the registration madness.

This is where the Convention Based Auto Registrations comes into the picture. Basically the team agree on a naming convention and use that convention to auto-wire the registrations as below.

public static void AutoWire(IUnityContainer container)
     var assemblies = AppDomain.CurrentDomain.GetAssemblies()
         .Where(s =>

     var types = from assembly in assemblies
                 from exptype in assembly.ExportedTypes
                 where exptype.Name.StartsWith("TypeNameStartWith")
                 select exptype;

     container.RegisterTypes(types, t => t.GetInterfaces(),

There are 2 conventions here – The assembly name and the type that need to be registered.
Both must start with an agreed naming convention. Once the convention is agreed and well defined, the container is almost invisible and importantly registration code is much more maintainable.

The above example uses Microsoft Unity Container. However similar techniques can be applied for other DI libraries.
Note that RegisterTypes only available in Unity version 3 and higher.

Let’s look at some practicality of the convention based approach
While it provides a great way to reduce configuration verbosity, it might not fit for all purposes. There might be situations where that we might still need a non-convention based approaches such as programmatic registrations or even configuration based registrations (in rare cases to support late binding). There is no rule to say that we can only use one approach. I think it is best to employ, first convention based, then programmatic registrations if required.

What if someone forget to use the naming convention?
It would result in a dependency resolution exception. Let’s assume there is no code reviews, and someone in the team had no idea about the convention based registration. Then included a non-convention based/explicit registrations as below..

container.RegisterType<TFrom, TTo>();

Again this is just a start of the same problem we saw before and we wanted to avoid it in the first place.

So how can we avoid it?
I thought of it would be nice to create a custom extension method on the container to verify the conventions are registered accordingly.


This extension method will look for the types that are already registered and check for the convention that we expect within each registered type.

public static class UnityExt
      public static void VerifyRegistrationConventions
                         (this IUnityContainer continer)
           var registrations = continer.Registrations
              .Where(x => !x.MappedToType.Name.StartsWith("Reg") &

           if (registrations.Any())
               var builder = new StringBuilder();
               builder.AppendLine("Registrations Convention Mismatch : ");
               foreach (var registration in registrations)
               builder.AppendLine("Registrations with the container
                         expects types name to be start with 'App': ");

               throw new ContainerConventionViolationException

This extension also assumes all registrations follow convention based registration.

The thrown exception message will contain the types that are not adhere to the specified naming convention.

Where we invoke this extension?
There are 2 possible places..
a. Last possible place that your application uses the DI container for object composition. In other words this extension can be used just after the last possible execution routine within the composition root.
b. First possible place just after the execution exited the composition root. This place may not be obvious as ‘a’, therefor I prefer ‘a’ over ‘b’

In both cases, the developer had every opportunity to construct the object graph and the above extension method would verify the conventions.

If we are making the DI container accessible outside the composition root, then we cannot guarantee that all types are composed within the Composition Root. In that case, we cannot utilise this extension reliably and importantly we are not using the DI container correctly.

Entity Framework updating (Code First) existing entity using foreign key Id(s) mistakes

Recently we have come across with a scenario like below.

We had an entity (EF bounded), and we wanted to update the entity’s foreign key references from an existing entity. For example, say..

A Person has a Brazilian Passport, and that person need to update the Passport to an American Passport.

The domain/entity model looks like this

 public class Person
   public int Id { get; set; }
   public string Name { get; set; }

   public virtual Passport Passport {get; set; }
   public int PassportId { get; set; }

public class Passport
  public int Id { get; set; }
  public string Number { get; set; }
  public string Nationality { get; set; }

Notice that Person has 2 properties relates to Passport foreign key references. One is a <a href=”; target=”_blank”>Navigational Property</a> and the other is the foreign key id reference. Notice that it uses the {EntityName}Id as the property name. It need to be in this convention for EF to generate the foreign key. If anything other than that EF would create an additional key.

Once you run the <a href=”; target=”_blank”>EF migration</a> you would see the tables generated as below..


Now in order to update the Person’s (only person) passport to an American passport, the code would be something like this..

 using (var dbContext = new PersonContext())
   Console.WriteLine("Update person with passport");
   var person = dbContext.Persons.First();
   var americanPassport = dbContext.Passports.
            Single(x => x.Nationality == "American");

   person.PassportId = americanPassport.Id; //Notice this line


I personally don’t like this approach for couple of reasons.

a. It feels “hacky” that you have set the id explicity to update the FK referece.
b. See the entity model, Passport. There are two properties roughly to achieve the same thing. If you use the Navigational Property you can access the Id right? So why we need another Id property?
c. Suddenly your domain entity become database ‘aware’ of FKs etc.

My preferred approach is to leave entity as it is, and just use the Navigational property. Unless if you really have to no the id property for some other reason, which I can’t think of.

 public class Person
    public int Id { get; set; }
    public string Name { get; set; }

    public virtual Passport Passport {get; set; }

That’s it! EF would generate the Foreign Key for Passport Entity as usual.

Now you can just update the entity using the Navigational Property (not the FK property id)

 using (var dbContext = new PersonContext())
    Console.WriteLine("Update person with passport");

    var person = dbContext.Persons.First();
    var americanPassport = dbContext.Passports.
        Single(x => x.Nationality == "American");
    person.Passport = americanPassport;


This is lot cleaner than setting up ID reference. To perform the update like this you need to make sure your, both entities (Person and Passport), are in unchanged State.

Unchanged: the entity is being tracked by the context and exists in the database, and its property values have not changed from the values in the database

Entity Framework Code First Automatic Migration & Existing Tables

We have been smooth sailing with EF6 Code First migration, but recently had few issues to dealt with migrating existing db tables.

Basically we have the below requirements.

  1. All new tables we create use Code First migration.  We want to avoid migration any existing db tables. Also we still want the EF mappings to configure for the existing tables, and have those entities in DbContext so we can work with those tables.
  2. We want to use the automatic migration. – this seems to be working well within the team environment.
  3. We want the migration to work only in our Dev Env, i.e not in QA, UAT, or Prod Envs.

Below are couple of  related SO questions..

The problem is that the EF migration does not appear to be seamlessly working with existing table structure.

When we run the automatic migration for the very first time, we want the existing table structure to be unchanged. But we also want the EF to be aware of the existing tables so we can perform operations on those tables.  It seems like we can only have one way or the other but not both.

Old and new Entities

(I have simplified the code so we can focus on the problem)

public class NewTable : BaseEntity
    public string Title { get; set; }

public class OldTable
     public int Id { get; set; }
     public string Name { get; set; }

BaseEntity contains some common properties such as ID, DateModified etc

Below is how the Mappings look like

    public class NewTableMap : EntityMap<NewTable>
        public NewTableMap()
            Property(x => x.Title).HasMaxLength(40);

    public class OldTableMap : EntityTypeConfiguration<OldTable>
        public OldTableMap()
            HasKey(t => t.Id);
            Property(x => x.Id).HasColumnName("fldId");

Note that I have explicitly specified the OldTable entity has been mapped to “OldTable” And the Id has the db column name “fldId”

DBContext has the standard operations including the model binding.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
     modelBuilder.Configurations.Add(new OldTableMap());
     modelBuilder.Configurations.Add(new NewTableMap());


The SQL Database would just have the old table

Since we starting from the scratch let’s enable the migration.

PM> Enable-Migrations -EnableAutomaticMigrations

The above command would create a new Migration Configuration with AutomaticMigration set to True.

We have not created any tables yet! So let’s run the migration command.

PM> Update-Database

We get the below error..
There is already an object named ‘OldTable’ in the database.

As you know there is our existing table in the db.
The script that EF creates had a CreateTable(“dbo.OldTable”), the migration throws the above error.

How can we tell the EF migration to ignore my OldTable??? Honestly don’t know the answer for this. This why the below work around may help you.

First create a specific migration.

PM> Add-Migration FirstMigration

This will create a migration script within the Migration folder. The script has 2 create table functions. One for the NewTable, one for the OldTable.

public override void Up()
                c => new
                        Id = c.Int(nullable: false, identity: true),
                        Title = c.String(maxLength: 40),
                        IsActive = c.Boolean(nullable: false),
                        DateModified = c.DateTime(nullable: false,
                                    precision: 7, storeType: "datetime2"),
                        DateCreated = c.DateTime(nullable: false,
                                    precision: 7, storeType: "datetime2"),
                        UserId = c.Guid(nullable: false),
                        MarkAsDeleted = c.Boolean(nullable: false),
                .PrimaryKey(t => t.Id);

                c => new
                        fldId = c.Int(nullable: false, identity: true),
                        Name = c.String(),
                .PrimaryKey(t => t.fldId);


If we were to run this migration (as above) we would get exactly the same error. So let’s modify the above migration script, for example by removing the CreateTable(“dbo.NewTable”,()… DropTable(“dbo.OldTable”); We leave the scripts for creation of new Tables as it is.

Now if you run the

PM> Update-Database
Specify the ‘-Verbose’ flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [201407120749125_FirstMigration].
Applying explicit migration: 201407120749125_FirstMigration.
Running Seed method.

Now if you check the database, the NewTable has been created and the existing table has not been changed.

Handling practical problems

It is very likely that someone else in your team has a different model changes to your model changes. If that’s the case, you also want to make sure that you don’t commit your initial migration script. You can treat it as your private migration script. This also assumes that you have non-shared database for development.

You team would also have to follow the same process. You can add this migration file to the exclusion list of the source control so the file won’t get committed to the repository.

Now you can make changes to the model as you would normally do and running the automatic migration would apply those changes accordingly.
It will never attempt to create your existing table as the automatic migration is now based on the modified FirstMigration. Subsequent migrations would use the last successful migration.

Just be cautious that in your next automatic migration…
Changing an entity which already mapped to an existing table would also make changes to the existing table.
If you use Ignore() method i.e ( Ignore(x => x.Name)) on the existing entity, it will also exclude that property from the existing table.
If you Ignore() method on the entire existing table during model binding i.e modelBuilder.Ignore(); it will just remove your exiting table. If this happens, simply remove the .Ignore and run the migration.


Keeping your C# code clean with Regionerate

I came across with this really nice VS add-in called Regionerate, which allows you to group various member types into regions. I’m a fan of keeping code tidy and this add-in really helps me to organise the code.
It works on Visual Studio 2010 and only works with C#.
You can download the Add-In from here.
Once you install this tool, you are ready to use the Regionerate.
You can also change the settings of Regionerate, go to Tools and click Regionerate Settings.
To use the Regionerate, simply use the Ctrl +R. You should see a window with few options as below. Alternatively just right click on Text Editor and select ‘Regionerate this’ from the context menu.

image a

As per the above options, you can create regions based on the member types (I.e public, private, and internal), regionalise by the member name, regionalise by the member type and the member name, order the members without and regions, and remove existing regions etc..

Below is a code sample on selecting the ‘Primary Code Layout’.

I strongly encourage you to have a look at this Add-In as it is very useful.

Working with Strings in C#.NET

Strings, strings and strings. They are all over in your application. You cannot avoid them at all. This article is about some tips on how you should use strings within your application. Most developers know these tips, but I still see some developers write inefficient code.


Before we drill into much deeper, would you recommend using String over string? For example…

String apple;
string apple;

Not really, string is simply an alias (shorthand) for the Common Type System (CTS) System.String class, which represents a sequence of characters. You can use them interchangeably in your code. For example…

String x = string.Copy("x");
string y = String.Copy("y");
<b>String concatenations</b>

Often developer concatenate string using + operator. Some developer use StringBuilder class in System.Text namespace.

string concat = "Apple" + ", " + "Orange";

StringBuilder sb = new StringBuilder();
sb.Append(", ");

So which one you should be using? It depends. For example if you have few strings that need to concatenate, then ‘+’ operator would just be fine. However if you have so many of them, it is better to use the StringBuilder class. The reason is that direct string concatenation will always consume more memory as it creates String objects for every instance that it creates. On the other hand StringBuilder is a complex type, which require instantiating once (also take up a negligible start-up time), and Append method is much faster, better CPU and efficient memory usage. Because of the tiny start up cost of instantiating StringBuilder class, it is preferable to use ‘+’ operators for when concatenating only few strings.

Below is an excellent article on string concatenations performances

“The conclusion to be drawn from these test results is really very straightforward. You should be using the StringBuilder class for all but the most trivial string concatenation (or replace) operations. The extra effort required to use the StringBuilder class is negligible and is far outweighed by the potential performance and scalability benefits to be gained. ”

Empty Strings

<pre>string a = "";
string c = String.Empty;

There is no much performance differences on any of these. If you want the maximum efficiency and better use of CPU memory use String.Empty. String.Empty is a static and read only field. It does not create any object. Because when you use an empty string “”, it still creates a new object. If you are performing a string comparison with an empty string, for example…

if (testString == String.Empty)
     testString = "Test string is empty";

if (StringA.Equals(String.Empty))
     testString = "Test string is empty"; 

if (testString.Length == 0)
      testString = " Test string is empty";

Some of you would argue the lack of readabilty on Legth == 0, but the truth is the Length comparison is the most efficient. If you need to check for null or empty string then String.IsNullOrEmpty() is also better on performances.

Securing your strings
Common string classes in .NET framework store string in memory. If you are dealing with very sensitive data, then storing in memory is not the most secure way. For this you need to use SecureString class which is System.Secure name space.

System.Security.SecureString secureString = new System.Security.SecureString();

Unfortunately you cannot assign a string to the secure class. Please find more information on Secure String below.

Compare Strings
Many developers tend to use the case insensitivity to compare two strings. This is not really efficient when comparing two strings.

if (testStringA.ToUpper() == testStringB.ToUpper())
     // Your code goes here

The regular expression engine in .NET is extremely good. but is not the most efficient method of simply comparing two strings. The below code is bit of a overkill.

var pattern = "Regex pattern.";
var string_value = "Hi! This is a test.";
var b = Regex.IsMatch(string_value, pattern);
Console.WriteLine("{0}", b);

However there is a much efficient way to compare strings using String.Compare method.

if (String.Compare(testStringA, testStringB, true) == 0)
      // Your code goes here

The below comparison does the same thing, but it is the most efficient.

if (String.Equals(StringA, StringB, StringComparison.OrdinalIgnoreCase))
	// Your code goes here                

More information is on ordinal string comparison is below.

String Literals and String Constants
I mentioned previously that string literals create a new string object. It doesn’t mean that you should not be using string literals at all. For example using string literals directly in your code assist readability of your code and have better performance than using string constants. Having said that if you have number of strings being used in you code over and over again, it is still better to define the string constants as the performance gain I mentioned above is not really significant. As you know changing strings in many places is often painful than declare it once, and use it wherever and wherever you want is lot easier.

private const string testString = "sampleString";
StringA = testString;

StringA = “sampleString” //efficient

The above are some of the examples that I tried by my self to prove better and efficient way of string manipulations. However there are many other string manipulations techniques which I haven’t mentioned here and worth trying. For example splitting strings, replacing strings, removing strings etc. It is very easy to check these operations, and all you need is micro-benchmarking fascilty. I use System.Diagnostics.Stopwatch class for benchmarking but there are other techniqes as well.

As a final note always be mindful when perform codding, and use these techinques so you would write efficient C# code.

Tips for converting VB.NET to C#

As soon as anyone sees this title, most of you would think, ‘Ah..that’s easy, use a tool and it will do the job for you’. Recently I have been given a small task to convert some VB.NET code to C#. I’m not good at writing VB.NET so this was a challenge.

As any other C# developer, I decided to use a conversion tool. I copied and paste the VB.NET code I needed to translate into C#.NET. Another approach would be to use the Refactor. If you can include this function in an assembly you can easily view the C# equivalent of the code using Refactor. I got it translated using a conversion tool. However I saw the translated code was bit confusing. Which also bring me to the next topic that you should not blindly translate your VB.NET code to C#.

Take a look at this example.


Public Function GetAppGUID(ByVal sectionId As String) As String 

Dim hexString As String = Nothing 
Dim i As Integer 
Dim guidlen As Integer 

guidlen = 16 

If sectionId.Length < guidlen Then 
sectionId = sectionId & New String(" ".Chars(0), guidlen - sectionId.Length) 
End If 

For i = 1 To guidlen 
hexString = hexString & Hex(Asc(Mid(sectionId, i, 1))) 

GetAppGUID = hexString 

End Function


public string GetAppGUID(string sectionId) 
	string hexString = null; 
	int i = 0; 
	int guidlen = 0; 
	guidlen = 16; 
	if (sectionId.Length < guidlen) { 
	        sectionId = sectionId + new string(" ".Chars(0), guidlen - sectionId.Length); 
	for (i = 1; i <= guidlen; i++) { 
	     hexString = hexString + Conversion.Hex(Strings.Asc(Strings.Mid(sectionId, i, 1))); 
	return hexString; 

As you can see the converted function require Microsoft.VisualBasic.dll for Conversion and Asc functions. In some cases yes you would use this dll but most of the time you don’t have to. You can easily write this function in C# using same line of code but not using Microsoft.VisualBasic.dll

private string GetAppGUID(string sectionId) 
        string hexString = null; 
        int i = 0; 
        int guidLength = 0; 
        guidLength = 16; 
        if (sectionId.Length < guidLength) 
            sectionId = sectionId + new string(" "[0], guidLength - sectionId.Length); 
        foreach (char c in sectionId) 
            int tmp = c; 
            hexString += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString())) 
        return hexString; 

So this is my opinion.

a. If you ever have to convert VB.NET to C#, you may use a conversion tool or Reflector but make sure you are not blindly converting the code.
b. If the converted code require Microsoft.VisualBasic.dll, then try to avoid this dll. Refactor your code to use the equivalent C# syntax. To include a completely different dll in your C# project for just a small method/syntax change is not really worth it.
c. Don’t take your task as “hell this is not the language I’m familiar with”. See this opportunity is an excellent way to learn another language. It is quite common in the industry that you get to do these types of tasks often. Which also prove you are an all-rounded developer,