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

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4