Register Types By Convention With Unity

Using Microsoft's Unity IoC container, you can register types by convention rather than having to explicitly register each interface to a concrete class. The convention is that interfaces beginning with "I" will map to concrete classes with the same name, minus the "I" (for example, interface IMyClass would map to concrete class MyClass). I only recently learned this, after watching a Pluralsight course that showed how to do the same thing using StructureMap. I'd used StructureMap a few years ago, but was unaware of this feature at the time, and am not sure if it existed then or not.

The example shown below will register types by convention (for example, uses of interface IMyClass yield concrete types of MyClass).

            container
            .RegisterTypes(
                AllClasses.FromLoadedAssemblies(),
                WithMappings.FromMatchingInterface,
                WithName.Default);

This cut down on the size of my Unity bootstrapping code significantly. J

Comments

Anonymous said…
RegisterTypes is not in the Unity version 4. Where did it go

Popular posts from this blog

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception

How To Mock Out Child Components In Unit Tests of Angular 2 Code