Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core

Introduction

 
You have an ASP.NET Core web project and you are using the built-in IoC container of ASP.NET Core to register and resolve your dependencies. Things look good and perfect; ASP.NET Core framework makes your life easy by providing its built-in IoC container. All you have to do is to reference your contract's project and service project in your web project or web layer and register your dependencies in Startup.cs file. I will inject the dependencies throughout the app wherever you needed.
 
Your Startup.cs file will typically look something like the following.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);  
  4.     services.AddScoped<IMyDependency, MyDependency>();  
  5.     services.AddTransient<IOperationTransient, Operation>();  
  6.     services.AddScoped<IOperationScoped, Operation>();  
  7.     services.AddSingleton<IOperationSingleton, Operation>();  
  8.     services.AddSingleton<IOperationSingletonInstance>(new Operation(Guid.Empty));  
  9.     services.AddTransient<OperationService, OperationService>();  
  10. }  
The only downside to this approach is that your web project will be referencing your service contracts/abstractions as well as service implementation project and your complete solution becomes tightly coupled. With time, the list of registration will keep on increasing.
 
Now, imagine you have multiple microservices. You want to replace one service with some other service, keeping the contracts intact, but still, you would have to modify your dependencies registered in Startup.cs file and hence re-compile your web project.
 
Ideally, the web layer should only know about the contracts and abstractions but not the actual implementations. But by registering your dependencies in Startup.cs, you will have to expose your implementations to the web project.
 
In this article, we will make our web project so loosely coupled that we could replace the old services with new services when needed without re-compiling or changing the existing registered services list by using MEF and built-in IoC container.
 
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core

MEF Based Approach

 
To de-couple our application we will take the help of MEF. The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. MEF can discover the components of our application by dynamically loading the DLLs and reading the attributes of the classes. If you want to dig more about MEF, I would suggest you visit the official MSDN documentation.
 

Getting your hands dirty

 
I think it would make more sense if we can see things in action. Let’s create an ASP.NET Core application. The project is going to be a sample Web API.
  • Create a WEB API project
  • Add three class library projects to the solution.
  • One will have all the contracts that are required for your application.
  • We have divided our services into two different projects.

    Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
Next, we will add a few contracts to our service contracts project.
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
  1. namespace ServiceContracts  
  2. {  
  3.     public interface IDummyService1  
  4.     {  
  5.         IEnumerable<string> GetDummyData();  
  6.     }  
  7. }    
  8. namespace ServiceContracts  
  9. {  
  10.     public interface IDummyService2  
  11.     {  
  12.         IEnumerable<string> GetDummyStrings();  
  13.     }  
  14. }  
Implement the contracts in Service layer.
Add service implementation in their respective projects.
  1. namespace ServiceOne  
  2. {  
  3.     public class DummyService1 : IDummyService1  
  4.     {  
  5.         public IEnumerable<string> GetDummyData()  
  6.         {  
  7.             return new List<string> { "data1""data2" };  
  8.         }  
  9.     }  
  10. }  
  11.   
  12. namespace ServiceTwo  
  13. {  
  14.     public class DummyService2 : IDummyService2  
  15.     {  
  16.         public IEnumerable<string> GetDummyStrings()  
  17.         {  
  18.             return new List<string> { "dummy1""dummy2" };  
  19.         }  
  20.     }  
  21. }  
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
 
Modify the default ‘ValuesController’ by injecting the service contracts in the constructor and exposing related endpoints.
  1. using ServiceContracts;  
  2.   
  3. namespace Sample.Controllers  
  4. {  
  5.     [Route("api/[controller]")]  
  6.     public class ValuesController : Controller  
  7.     {  
  8.         private readonly IDummyService1 dummyService1;  
  9.         private readonly IDummyService2 dummyService2;  
  10.   
  11.         public ValuesController(IDummyService1 dummyService1, IDummyService2 dummyService2)  
  12.         {  
  13.             this.dummyService1 = dummyService1;  
  14.             this.dummyService2 = dummyService2;  
  15.         }  
  16.   
  17.   
  18.         [HttpGet("data")]  
  19.         public IEnumerable<string> GetData()  
  20.         {  
  21.             return dummyService1.GetDummyData();  
  22.         }  
  23.   
  24.         [HttpGet("strings")]  
  25.         public IEnumerable<string> GetStrings()  
  26.         {  
  27.             return dummyService2.GetDummyStrings();  
  28.         }  
  29.   
  30.         // GET api/values  
  31.         [HttpGet]  
  32.         public IEnumerable<string> Get()  
  33.         {  
  34.             return new string[] { "value1""value2" };  
  35.         }  
  36.     }  
  37. }  
Keep in mind we have not registered our dependencies in Startup file yet.
 

Registering dependencies via MEF

 
Add a new class library project.
 
Add an interface which will expose some wrapper methods of ‘IServiceCollection’
  1. public interface IDependencyRegister  
  2. {  
  3.         void AddScoped<TService>() where TService : class;  
  4.   
  5.         void AddScoped<TService, TImplementation>()  
  6.             where TService : class  
  7.             where TImplementation : class, TService;  
  8.   
  9.         void AddSingleton<TService>() where TService : class;  
  10.   
  11.         void AddSingleton<TService, TImplementation>()  
  12.             where TService : class  
  13.             where TImplementation : class, TService;  
  14.   
  15.         void AddTransient<TService>() where TService : class;  
  16.   
  17.         void AddTransient<TService, TImplementation>()  
  18.             where TService : class  
  19.             where TImplementation : class, TService;  
  20.   
  21.         void AddTransientForMultiImplementation<TService, TImplementation>()  
  22.             where TService : class  
  23.             where TImplementation : class, TService;  
  24.   
  25.         void AddScopedForMultiImplementation<TService, TImplementation>()  
  26.             where TService : class  
  27.             where TImplementation : class, TService;  
  28.  }  
Add another interface which will be used to register dependencies.
  1. public interface IDependencyResolver  
  2. {  
  3.     void SetUp(IDependencyRegister dependencyRegister);  
  4. }  
Time to give implementation to IDependencyRegister
  1. using Microsoft.Extensions.DependencyInjection;  
  2.   
  3. namespace vDependencyResolver  
  4. {  
  5.     public class DependencyRegister : IDependencyRegister  
  6.     {  
  7.         private readonly IServiceCollection serviceCollection;  
  8.   
  9.         public DependencyRegister(IServiceCollection serviceCollection)  
  10.         {  
  11.             this.serviceCollection = serviceCollection;  
  12.         }  
  13.   
  14.         void IDependencyRegister.AddScoped<TService>()  
  15.         {  
  16.             serviceCollection.AddScoped<TService>();  
  17.         }  
  18.   
  19.         void IDependencyRegister.AddScoped<TService, TImplementation>()  
  20.         {  
  21.             serviceCollection.AddScoped<TService, TImplementation>();  
  22.         }  
  23.   
  24.         void IDependencyRegister.AddScopedForMultiImplementation<TService, TImplementation>()  
  25.         {  
  26.             serviceCollection.AddScoped<TImplementation>()  
  27.                 .AddScoped<TService, TImplementation>(s => s.GetService<TImplementation>());  
  28.         }  
  29.   
  30.         void IDependencyRegister.AddSingleton<TService>()  
  31.         {  
  32.             serviceCollection.AddSingleton<TService>();  
  33.         }  
  34.   
  35.         void IDependencyRegister.AddSingleton<TService, TImplementation>()  
  36.         {  
  37.             serviceCollection.AddSingleton<TService, TImplementation>();  
  38.         }  
  39.   
  40.         void IDependencyRegister.AddTransient<TService>()  
  41.         {  
  42.             serviceCollection.AddTransient<TService>();  
  43.         }  
  44.   
  45.         void IDependencyRegister.AddTransient<TService, TImplementation>()  
  46.         {  
  47.             serviceCollection.AddTransient<TService, TImplementation>();  
  48.         }  
  49.   
  50.         void IDependencyRegister.AddTransientForMultiImplementation<TService, TImplementation>()  
  51.         {  
  52.             serviceCollection.AddTransient<TImplementation>()  
  53.                 .AddTransient<TService, TImplementation>(s => s.GetService<TImplementation>());  
  54.         }  
  55.     }  
  56. }  
IServiceCollection is found in Microsoft.Extensions.DependencyInjection.Abstractions dll.
 
Now it's time to see the magic of MEF. Add DependencyLoader class.
  1. public static class DependencyLoader  
  2. {  
  3.     public static void LoadDependencies(this IServiceCollection serviceCollection, string path, string pattern)  
  4.     {  
  5.         var dirCat = new DirectoryCatalog(path, pattern);  
  6.         var importDef = BuildImportDefinition();  
  7.         try  
  8.         {  
  9.             using (var aggregateCatalog = new AggregateCatalog())  
  10.             {  
  11.                 aggregateCatalog.Catalogs.Add(dirCat);  
  12.   
  13.                 using (var componsitionContainer = new CompositionContainer(aggregateCatalog))  
  14.                 {  
  15.                     IEnumerable<Export> exports = componsitionContainer.GetExports(importDef);  
  16.   
  17.                     IEnumerable<IDependencyResolver> modules =  
  18.                         exports.Select(export => export.Value as IDependencyResolver).Where(m => m != null);  
  19.   
  20.                     var registerComponent = new DependencyRegister(serviceCollection);  
  21.                     foreach (IDependencyResolver module in modules)  
  22.                     {  
  23.                         module.SetUp(registerComponent);  
  24.                     }  
  25.                 }  
  26.             }  
  27.         }  
  28.         catch (ReflectionTypeLoadException typeLoadException)  
  29.         {  
  30.             var builder = new StringBuilder();  
  31.             foreach (Exception loaderException in typeLoadException.LoaderExceptions)  
  32.             {  
  33.                 builder.AppendFormat("{0}\n", loaderException.Message);  
  34.             }  
  35.   
  36.             throw new TypeLoadException(builder.ToString(), typeLoadException);  
  37.         }  
  38.     }  
  39.   
  40.     private static ImportDefinition BuildImportDefinition()  
  41.     {  
  42.         return new ImportDefinition(  
  43.             def => truetypeof(IDependencyResolver).FullName, ImportCardinality.ZeroOrMore, falsefalse);  
  44.     }  
  45. }  
LoadDependencies will be used as extension method in Startup file to tell MEF where to load dlls.
 
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
 
Well, we are almost there, now all that is left is to register our dependencies in the Service layer itself. To do so, we will implement the interface ‘IDependencyResolver’ and use MEF Export attribute to let MEF discover the registration code.
 
Add class in ServiceOne project & ServiceTwo project,
  1. using ServiceContracts;  
  2. using System.ComponentModel.Composition;  
  3. using vDependencyResolver;  
  4.   
  5. namespace ServiceOne  
  6. {  
  7.     [Export(typeof(IDependencyResolver))]  
  8.     public class ServiceOneDependencyResolver : IDependencyResolver  
  9.     {  
  10.         public void SetUp(IDependencyRegister dependencyRegister)  
  11.         {  
  12.             dependencyRegister.AddScoped<IDummyService1, DummyService1>();  
  13.         }  
  14.     }  
  15. }  
  16.   
  17. using ServiceContracts;  
  18. using System.ComponentModel.Composition;  
  19. using vDependencyResolver;  
  20.   
  21. namespace ServiceTwo  
  22. {  
  23.     [Export(typeof(IDependencyResolver))]  
  24.     public class ServiceTwoDependencyResolver : IDependencyResolver  
  25.     {  
  26.         public void SetUp(IDependencyRegister dependencyRegister)  
  27.         {  
  28.             dependencyRegister.AddScoped<IDummyService2, DummyService2>();  
  29.         }  
  30.     }  
  31. }  
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
 
One last thing -- set the project properties of Service projects to compile DLLs to web bin folder. Service DLLs will be compiled and saved in the web bin folder.
 
In Startup file, we will use extension created previously.
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             services.AddMvc();  
  4.             services.LoadDependencies(Configuration["DI:Path"], Configuration["DI:ServiceOne:Dll"]);  
  5.             services.LoadDependencies(Configuration["DI:Path"], Configuration["DI:ServiceTwo:Dll"]);  
  6.         }  
Don’t forget to add new entries in appsettings.json.
  1. "DI": {  
  2.   "Path"".\\bin\\Debug\\netcoreapp2.0",  
  3.   "ServiceOne": {  
  4.     "Dll""ServiceOne.dll"  
  5.   },  
  6.   "ServiceTwo": {  
  7.     "Dll""ServiceTwo.dll"  
  8.   }  
  9. }  
Path key holds the value of the location of service DLLs. And ServiceOne holds the name of “ServiceOne.dll” and ServiceTwo holds the name of “ServiceTwo.dll”.
 
Run the application and hit the URLs,
  • http://localhost:56121/api/values/data
  • http://localhost:56121/api/values/strings
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
Wow, isn’t it beautiful!
 
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
 
Our web layer only contains the reference of the Contracts project and is totally unaware about the service layer, so it's loosely coupled.
 
The story doesn’t end here; let's see the real magic of all the hard work we just did. We will add a new service project which will also implement the ‘IDummyService1’ and replace the older service with new service without even re-compiling the web project. Services are now pluggable into the web layer without any registration in Startup.cs file or re-compiling the project. We will make it configurable by using the appsettings.json.
 
Resolve Dependencies Using MEF And Built-In IoC Container Of ASP.NET Core
  1. using ServiceContracts; 
  2. using System.Collections.Generic;  
  3.   
  4. namespace NewService  
  5. {  
  6.     public class NewService : IDummyService1  
  7.     {  
  8.         public IEnumerable<string> GetDummyData()  
  9.         {  
  10.             return new List<string> { "data from new service" };  
  11.         }  
  12.     }  
  13. }  
Add ServiceDependecyResolver.
  1. using ServiceContracts;  
  2. using System.ComponentModel.Composition;  
  3. using vDependencyResolver;  
  4.   
  5. namespace NewService  
  6. {  
  7.     [Export(typeof(IDependencyResolver))]  
  8.     public class ServiceDependencyResolver : IDependencyResolver  
  9.     {  
  10.         public void SetUp(IDependencyRegister dependencyRegister)  
  11.         {  
  12.             dependencyRegister.AddScoped<IDummyService1, NewService>();  
  13.         }  
  14.     }  
  15. }  
Build the complete project and the run again.
 
If you hit the URL (http://localhost:56121/api/values/data) data from DummyService1 will be loaded.
 
Stop the application and modify the appsettings.json file.
  1. "DI": {  
  2.   "Path"".\\bin\\Debug\\netcoreapp2.0",  
  3.   "ServiceOne": {  
  4.     "Dll""NewService.dll"  
  5.   },  
  6.   "ServiceTwo": {  
  7.     "Dll""ServiceTwo.dll"  
  8.   }  
  9. }  
Now, data will be loaded from NewService service without re-compiling or changing anything in any project or Startup file. That’s the magic I was talking about.
 

Source Code

 
You can find the source code on GitHub.
 

NuGet Package

 
I have also created a Nuget package named ‘vDependencyResolver’ to be directed by services and web projects. You can find the same at here.
 

Conclusion

 
We can keep our architecture clean by keeping services abstracted to the Web layer.