Filtering and registering all types using Autofac IoC
01 Aug 2016
Autofac IoC helps you to automatically register all your types from any assembly. Easiest way would be
builder.RegisterAssemblyTypes(AppDomain.CurrentDomain.GetAssemblies())
.Where(t => t.Name.EndsWith("Repository"))
.AsImplementedInterfaces()
.InstancePerRequest();
In case you don't have a separate DLL, and your types are just separated by namespaces within same DLL.
Then following code will help you to find a particular assembly by its name, and then to register all types within that assembly that matches the format
assemblyname.typename*
private static void RegisterCustomTypes(ContainerBuilder builder)
{
string[] myAssemblies = { "Com.MyNamespace", "Com.MyNamespace2" };
string[][] typesToRegister = {
new string[] { "business" },
new string[] { "utility", "datalayer"}
};
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
int idx = 0;
foreach (var assembly in myAssemblies)
{
var cAssembly = assemblies
.Where(a => a.FullName.StartsWith(assembly, StringComparison.InvariantCultureIgnoreCase))
.FirstOrDefault();
var types = cAssembly.GetTypes().Where(t =>
typesToRegister[idx].Where(r => t.FullName
.StartsWith(assembly + "." + r, StringComparison.InvariantCultureIgnoreCase)).Any());
types = types.Where(t => t.IsPublic && !t.IsAbstract);
builder.RegisterTypes(types.ToArray()).AsSelf().InstancePerRequest();
idx++;
}
}
The above code gives you the flexibility to register types from multiple target assemblies based on filtering the required type names.
Let me know your views