Resolve dependency of dependencies using Inversion of Control and dependency injection in ASP.NET Web APIs with Unity Container and Managed Extensibility Framework (MEF)
In my last two articles I explained how to create a RESTful service using ASP.NET Web API working with Entity Framework and resolving dependencies using Unity Container. In this article I’ll explain how to create a loosely coupled system with Unity Container and MEF(Managed Extensibility Framework) using Inversion of Control. I’ll not be explaining much theory but rather focus more on practical implementations. For the readers who are following this series, they can use their existing solution that they have created till time. For my new readers of this article, I have provided the download link for the previous source code and current source code as well.
For theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of Control(IOC).
Murach: An introduction to web programming with ASP.NET Core MVCMahmoudOHassouna
Murach: An introduction to web programming with ASP.NET Core MVC
Mary Delamater, Joel Murach - Murach's ASP.NET Core MVC-Mike Murach & Associates, Inc. (2020) (1)
Murach: An introduction to web programming with ASP.NET Core MVCMahmoudOHassouna
Murach: An introduction to web programming with ASP.NET Core MVC
Mary Delamater, Joel Murach - Murach's ASP.NET Core MVC-Mike Murach & Associates, Inc. (2020) (1)
In this session I have described the different types of dependency injections and their usages.
Reference Link : http://en.wikipedia.org/wiki/Dependency_injection
This article is about aspect oriented programming (aop) in spring. the related example of an application with aop support is in the following address :
https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example
Mvc interview questions – deep dive jinal desaijinaldesailive
Can you describe ASP.NET MVC Request Life Cycle? 1. Receive request, look up Route object in RouteTable collection and create RouteData object. 2. Create RequestContext instance. 3. Create MvcHandler and pass RequestContext to handler. 4. Identify IControllerFactory from RequestContext. 5. Create instance of class that implements ControllerBase. 6. Call MyController.Execute method. 7. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view.
This session describes the overview on different types of spring containers. Here we can also find simple examples showing the demo to instantiate the containers.
Inversion of control using dependency injection in Web APIs using Unity Conta...Akhil Mittal
My article will explain how we can make our Web API service architecture loosely coupled and more flexible. We already learnt that how we can create a RESTful service using Asp.net Web API and Entity framework in my last article. If you remember we ended up in a solution with a design flaw, we’ll try to overcome that flaw by resolving the dependencies of dependent components. For those who have not followed my previous article, they can learn by having the sample project attached as a test application from my first article.
In this session I have described the different types of dependency injections and their usages.
Reference Link : http://en.wikipedia.org/wiki/Dependency_injection
This article is about aspect oriented programming (aop) in spring. the related example of an application with aop support is in the following address :
https://github.com/ghorbanihamid/SpringBoot_AOP_JPA_Example
Mvc interview questions – deep dive jinal desaijinaldesailive
Can you describe ASP.NET MVC Request Life Cycle? 1. Receive request, look up Route object in RouteTable collection and create RouteData object. 2. Create RequestContext instance. 3. Create MvcHandler and pass RequestContext to handler. 4. Identify IControllerFactory from RequestContext. 5. Create instance of class that implements ControllerBase. 6. Call MyController.Execute method. 7. The ControllerActionInvoker determines which action to invoke on the controller and executes the action on the controller, which results in calling the model and returning a view.
This session describes the overview on different types of spring containers. Here we can also find simple examples showing the demo to instantiate the containers.
Inversion of control using dependency injection in Web APIs using Unity Conta...Akhil Mittal
My article will explain how we can make our Web API service architecture loosely coupled and more flexible. We already learnt that how we can create a RESTful service using Asp.net Web API and Entity framework in my last article. If you remember we ended up in a solution with a design flaw, we’ll try to overcome that flaw by resolving the dependencies of dependent components. For those who have not followed my previous article, they can learn by having the sample project attached as a test application from my first article.
State Management In ASP.NET And ASP.NET MVCjinaldesailive
As we all know HTML is stateless language. It cannot persist state, so every web development framework provides facility to maintain state in one way or another way. There are different techniques available for state management in ASP.NET and ASP.NET MVC. Following is summary of all such techniques for maintaining state.
Get More on http://www.ManzoorTheTrainer.com
This eBook contains 109 important interview questions along with answers that any web developer looking for a job on MS.Net platform needs to know. This eBook starts with two articles one of which talks about why most of the engineers are jobless and the other say the solution for it. As a technical part I have covered the following MS.Net technologies ASP.Net, C#.Net & ADO.Net and MS SQL Server.
Second edition is also on the way with focus on at least one real time example on each question.
Key features: Point to point | Simple language
ASP.NET MVC Interview Questions and Answers by Shailendra ChauhanShailendra Chauhan
This book covers useful Interview Questions and Answers on ASP.NET MVC. This book is appropriate for novice as well as for senior level professionals who wants to strengthen their skills before appearing for an interview on ASP.NET MVC. This book is equally helpful to sharpen their programming skills and understanding ASP.NET MVC in a short time.
Similar to Resolve dependency of dependencies using Inversion of Control and dependency injection in ASP.NET Web APIs with Unity Container and Managed Extensibility Framework (MEF)
This paper’s aim is to point out the RAD ( Rapid application development) elements present in the Microsoft’s MVC 3 and WCF 4.0 using Microsoft Visual Studio 2010. It will describe why creating a new web application using MVC 3 and WCF 4.0 is a easy and fast and also present simple ways to develop such applications.
Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIsAkhil Mittal
We have already learnt a lot on WebAPI. I have already explained how to create WebAPI, connect it with database using Entity Framework, resolving dependencies using Unity Container as well as using MEF. In all our sample applications we were using default route that MVC provides us for CRUD operations. In this article I’ll explain how to write your own custom routes using Attribute Routing. We’ll deal with Action level routing as well as Controller level routing. I’ll explain this in detail with the help of a sample application. My new readers can use any Web API sample they have, else you can also use the sample applications we developed in my previous articles.
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
A developer has been working on an ASP.NET Core project for a few months. During that time he had various problems I had to fix. Then he converted his application to the RC2 version that was released a few weeks ago. Here we write down a post listing problems that could be fixed. Hope a few would find it useful.
Similar to Resolve dependency of dependencies using Inversion of Control and dependency injection in ASP.NET Web APIs with Unity Container and Managed Extensibility Framework (MEF) (20)
Diving in OOP (Day 1) : Polymorphism and Inheritance (Early Binding/Compile T...Akhil Mittal
I have been writing a lot about advanced topics like MVC, Entity Framework, Repository Patterns etc., my priority always remains to cover the topic as a whole, so that a reader do not have to search for missing links anywhere else. My this article will cover almost every OOPS concept that a novice/beginner developer hunt for, and not only beginners, the article’s purpose is to be helpful to experience professionals also who need to sometimes brush-up their concepts or who prepare for interviews .
Diving in OOP (Day 6): Understanding Enums in C# (A Practical Approach)Akhil Mittal
My article of the series “Diving in OOP” will explain enum datatype in C#. We’ll learn by doing hands on lab and not only by theory. We’ll explore the power of enum and will cover almost every scenario in which we can use enum. We’ll follow a practical approach of learning to understand this concept. We may come across complex examples to understand the concept more deeply.
Diving into OOP (Day 5): All About C# Access Modifiers (Public/Private/Protec...Akhil Mittal
Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
A tale of scale & speed: How the US Navy is enabling software delivery from l...sonjaschweigert1
Rapid and secure feature delivery is a goal across every application team and every branch of the DoD. The Navy’s DevSecOps platform, Party Barge, has achieved:
- Reduction in onboarding time from 5 weeks to 1 day
- Improved developer experience and productivity through actionable findings and reduction of false positives
- Maintenance of superior security standards and inherent policy enforcement with Authorization to Operate (ATO)
Development teams can ship efficiently and ensure applications are cyber ready for Navy Authorizing Officials (AOs). In this webinar, Sigma Defense and Anchore will give attendees a look behind the scenes and demo secure pipeline automation and security artifacts that speed up application ATO and time to production.
We will cover:
- How to remove silos in DevSecOps
- How to build efficient development pipeline roles and component templates
- How to deliver security artifacts that matter for ATO’s (SBOMs, vulnerability reports, and policy evidence)
- How to streamline operations with automated policy checks on container images
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...SOFTTECHHUB
The choice of an operating system plays a pivotal role in shaping our computing experience. For decades, Microsoft's Windows has dominated the market, offering a familiar and widely adopted platform for personal and professional use. However, as technological advancements continue to push the boundaries of innovation, alternative operating systems have emerged, challenging the status quo and offering users a fresh perspective on computing.
One such alternative that has garnered significant attention and acclaim is Nitrux Linux 3.5.0, a sleek, powerful, and user-friendly Linux distribution that promises to redefine the way we interact with our devices. With its focus on performance, security, and customization, Nitrux Linux presents a compelling case for those seeking to break free from the constraints of proprietary software and embrace the freedom and flexibility of open-source computing.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Communications Mining Series - Zero to Hero - Session 1
Resolve dependency of dependencies using Inversion of Control and dependency injection in ASP.NET Web APIs with Unity Container and Managed Extensibility Framework (MEF)
1. RESTful Day #3: Resolve dependency of
dependencies using Inversion of Control
and dependency injection in Asp.net Web
APIs with Unity Container and Managed
Extensibility Framework (MEF)
–by Akhil Mittal
Table of Contents
Table of Contents _________________________________________________________________________ 1
Introduction _____________________________________________________________________________ 1
Roadmap _______________________________________________________________________________ 2
Existing Design and Problem ________________________________________________________________ 2
Managed Extensibility Framework (MEF)______________________________________________________ 4
Creating a Dependency Resolver with Unity and MEF ____________________________________________ 4
Setup Business Services ____________________________________________________________________ 9
Setup DataModel ________________________________________________________________________ 11
Setup REST endpoint / WebAPI project_______________________________________________________ 12
Running the application___________________________________________________________________ 15
Advantages of this design _________________________________________________________________ 21
Conclusion______________________________________________________________________________ 22
Introduction
In my last two articles I explained how to create a RESTful service using Asp.Net Web API working with Entity
Framework and resolving dependencies using Unity Container. In this article I’ll explain how to create a loosely
coupled system with Unity Container and MEF(Managed Extensibility Framework) using Inversion of Control.
I’ll not be explaining much theory but rather focus more on practical implementations. For the readers who
are following this series, they can use their existing solution that they have created till time. For my new
readers of this article, I have provided the download link for the previous source code and current source code
as well.
2. For theory and understanding of DI and IOC you can follow the following links: Unity and Inversion of
Control(IOC).
Roadmap
Here is my roadmap for learning RESTful APIs,
RESTful Day #1: Enterprise level application architecture with Web API’s using Entity Framework, Generic
Repository pattern and Unit of Work.
RESTful Day #2: Inversion of control using dependency injection in Web API's using Unity Container and
Bootstrapper.
RESTful Day #3: Resolve dependency of dependencies using Inversion of Control and dependency injection in
Asp.net Web APIs with Unity Container and Managed Extensibility Framework (MEF).
RESTful Day #4: Custom URL Re-Writing/Routing using Attribute Routes in MVC 4 Web APIs.
RESTful Day #5: Token based custom authorization in Web API’s using Action Filters.
RESTful Day #6: Request logging and Exception handing/logging in Web API’s using Action Filters, Exception
Filters and nLog.
RESTful Day #7: Unit testing Asp.Net Web API's controllers using nUnit.
RESTful Day #8: Extending OData support in Asp.Net Web API's.
I’ll purposely use Visual Studio 2010 and .net Framework 4.0 because there are few implementations that are
very hard to find in .Net Framework 4.0, but I’ll make it easy by showing how we can do it.
Existing Design and Problem
We already have an existing design. If you open the solution, you’ll get to see the structure as mentioned
below,
3. We tried to design a loosely coupled architecture in the following way,
DataModel (responsible for communication with database) : Only talks to service layer.
Services (acts as a business logic layer between REST endpoint and data access) : Communicates
between REST endpoint and DataModel.
REST API i.e. Controllers: Only talks to services via the interfaces exposed.
But when we tried to resolve the dependency of UnitOfWork from Services, we had to reference DataModel
dll in to our WebAPI project; this violated our system like shown in following image,
4. In this article we’ll try to resolve dependency (data model) of a dependency (services) from our existing
solution. My controller depended on services and my services depended on data model. Now we’ll design an
architecture in which components will be independent of each other in terms of object creation and
instantiation. To achieve this we’ll make use of MEF(Managed Extensibility Framework) along with Unity
Container and reflection.
Image source : http://o5.com/wp-content/uploads/2010/08/dreamstime_15583711-550x371.jpg
Ideally, we should not be having the below code in our Bootstrapper class,
container.RegisterType<IProductServices, ProductServices>().RegisterType<UnitOfWork>(new
HierarchicalLifetimeManager());
Managed Extensibility Framework (MEF)
You can have a read about Unity from msdn link. I am just quoting some lines from msdn,
“The Managed Extensibility Framework or MEF is a library for creating lightweight, extensible applications. It
allows application developers to discover and use extensions with no configuration required. It also lets extension
developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be
reused within applications, but across applications as well.”
“MEF is an integral part of the .NET Framework 4, and is available wherever the .NET Framework is used. You can
use MEF in your client applications, whether they use Windows Forms, WPF, or any other technology, or in server
applications that use ASP.NET.”
Creating a Dependency Resolver with Unity and MEF
Open your Visual studio, I am using VS 2010, you can use VS version 2010 or above. Load the solution.
Step 1: Right click solution explorer and add a new project named Resolver,
5. I have intentionally chosen this name, and you already know it why
Step 2: Right click Resolver project and click on ManageNugetPackage, in the interface of adding new package,
search Unity.MVC3 in online library,
Install the package to your solution.
Step 3: Right click resolver project and add a reference to System.ComponentModel.Composition.
You can find the dll into your GAC.I am using framework 4.0, so referring to the same version dll.
6. This dll is the part of MEF and is already installed with .net Framework 4.0 in the system GAC. This dll provides
classes that are very core of MEF.
Step 4: Just add an interface named IComponent to Resolver project that contains the initialization method
named Setup. We’ll try to implement this interface into our Resolver class that we’ll create in our other
projects like DataModel, Services and WebApI.
namespace Resolver
{
/// <summary>
/// Register underlying types with unity.
/// </summary>
public interface IComponent
{
}
}
Step 5: Before we declare our Setup method, just add one more interface responsible for serving as a contract
to register types. I name this interface as IRegisterComponent,
namespace Resolver
{
/// <summary>
/// Responsible for registering types in unity configuration by implementing IComponent
/// </summary>
public interface IRegisterComponent
{
/// <summary>
/// Register type method
/// </summary>
/// <typeparam name="TFrom"></typeparam>
/// <typeparam name="TTo"></typeparam>
/// <param name="withInterception"></param>
void RegisterType<TFrom, TTo>(bool withInterception = false) where TTo : TFrom;
/// <summary>
/// Register type with container controlled life time manager
/// </summary>
7. /// <typeparam name="TFrom"></typeparam>
/// <typeparam name="TTo"></typeparam>
/// <param name="withInterception"></param>
void RegisterTypeWithControlledLifeTime<TFrom, TTo>(bool withInterception = false)
where TTo : TFrom;
}
}
In this interface I have declared two methods, one RegisterType and other in to RegisterType with Controlled
life time of the object, i.e. the life time of an object will be hierarchal in manner. This is kind of same like we do
in Unity.
Step 6: Now declare Setup method on our previously created IComponent interface, that takes instance of
IRegisterComponent as a parameter,
void SetUp(IRegisterComponent registerComponent);
So our IComponent interface becomes,
namespace Resolver
{
/// <summary>
/// Register underlying types with unity.
/// </summary>
public interface IComponent
{
void SetUp(IRegisterComponent registerComponent);
}
}
Step 6: Now we’ll write a packager or you can say a wrapper over MEF and Unity to register types/
components. This is the core MEF implementation. Create a class named ComponentLoader, and add
following code to it,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Reflection;
namespace Resolver
{
public static class ComponentLoader
{
public static void LoadContainer(IUnityContainer container, string path, string
pattern)
{
var dirCat = new DirectoryCatalog(path, pattern);
var importDef = BuildImportDefinition();
try
8. {
using (var aggregateCatalog = new AggregateCatalog())
{
aggregateCatalog.Catalogs.Add(dirCat);
using (var componsitionContainer = new
CompositionContainer(aggregateCatalog))
{
IEnumerable<Export> exports =
componsitionContainer.GetExports(importDef);
IEnumerable<IComponent> modules =
exports.Select(export => export.Value as IComponent).Where(m => m
!= null);
var registerComponent = new RegisterComponent(container);
foreach (IComponent module in modules)
{
module.SetUp(registerComponent);
}
}
}
}
catch (ReflectionTypeLoadException typeLoadException)
{
var builder = new StringBuilder();
foreach (Exception loaderException in typeLoadException.LoaderExceptions)
{
builder.AppendFormat("{0}n", loaderException.Message);
}
throw new TypeLoadException(builder.ToString(), typeLoadException);
}
}
private static ImportDefinition BuildImportDefinition()
{
return new ImportDefinition(
def => true, typeof(IComponent).FullName, ImportCardinality.ZeroOrMore,
false, false);
}
}
internal class RegisterComponent : IRegisterComponent
{
private readonly IUnityContainer _container;
public RegisterComponent(IUnityContainer container)
{
this._container = container;
//Register interception behaviour if any
}
public void RegisterType<TFrom, TTo>(bool withInterception = false) where TTo : TFrom
{
if (withInterception)
9. {
//register with interception
}
else
{
this._container.RegisterType<TFrom, TTo>();
}
}
public void RegisterTypeWithControlledLifeTime<TFrom, TTo>(bool withInterception =
false) where TTo : TFrom
{
this._container.RegisterType<TFrom, TTo>(new
ContainerControlledLifetimeManager());
}
}
}
Step 7 :Now our Resolver wrapper is ready.Build the project and add its reference to DataModel,
BusinessServices and WebApi project like shown below,
Setup Business Services
We already have added reference of Resolver in BusinessServices project. We agreed to implement
IComponent interface in each of our project.
10. So create a class named DependencyResolver and implement IComponent interface into it, we make use of
reflection too to import IComponent type. So add a class and add following code to that DependencyResolver
class,
using System.ComponentModel.Composition;
using DataModel;
using DataModel.UnitOfWork;
using Resolver;
namespace BusinessServices
{
[Export(typeof(IComponent))]
public class DependencyResolver : IComponent
{
public void SetUp(IRegisterComponent registerComponent)
{
registerComponent.RegisterType<IProductServices, ProductServices>();
}
}
}
Note that we have implemented SetUp method and in the same method we registered type for my
ProductService.
All of the existing code base remains same.We don’t need to touch the IProductServices interface or
ProductServices class.
11. Setup DataModel
We have added Resolver project reference to DataModel project as well. So we’ll try to register the type of
UnitOfWork in this project.We proceed in same fashion, just add a DependencyResolver class and implement
its Setup method to register type of UnitOfWork.To make the code more readable and standard, I made a
change.I just added an interface for UnitOfWork and named it IUnitOfWork.Now my UnitOfWork class derives
from this, you can do this exercise in earlier versions of projects we discussed in first two articles.
So my IUnitOfWork contains declaration of a single public method in UnitOfWork,
namespace DataModel.UnitOfWork
{
public interface IUnitOfWork
{
/// <summary>
/// Save method.
/// </summary>
void Save();
}
}
Now register the type for UnitOfWork in DepenencyResolver class, our class becomes as shown below,
using System.ComponentModel.Composition;
using System.Data.Entity;
using DataModel.UnitOfWork;
using Resolver;
namespace DataModel
{
[Export(typeof(IComponent))]
public class DependencyResolver : IComponent
{
public void SetUp(IRegisterComponent registerComponent)
{
registerComponent.RegisterType<IUnitOfWork,UnitOfWork.UnitOfWork>();
}
}
}
12. Again, no need to touch any existing code of this project.
Setup REST endpoint / WebAPI project
Our 90% of the job is done.
We now need to setup or WebAPI project.We’ll not add any DependencyResolver class in this project.We’ll
invert the calling mechanism of layers in Bootstrapper class that we already have, so when you open your
bootstrapper class, you’ll get the code something like,
using System.Web.Http;
using System.Web.Mvc;
using BusinessServices;
using DataModel.UnitOfWork;
using Microsoft.Practices.Unity;
using Unity.Mvc3;
namespace WebApi
13. {
public static class Bootstrapper
{
public static void Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// register dependency resolver for WebAPI RC
GlobalConfiguration.Configuration.DependencyResolver = new
Unity.WebApi.UnityDependencyResolver(container);
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
container.RegisterType<IProductServices,
ProductServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());
return container;
}
}
}
Now, we need to change the code base a bit to make our system loosely coupled.Just remove the reference
of DataModel from WebAPI project.
We don’t want our DataModel to be exposed to WebAPI project, that was our aim though, so we cut down
the dependency of DataModel project now.
Add following code of Bootstrapper class to the existing Bootstarpper class,
14. using System.Web.Http;
//using DataModel.UnitOfWork;
using Microsoft.Practices.Unity;
using Resolver;
using Unity.Mvc3;
namespace WebApi
{
public static class Bootstrapper
{
public static void Initialise()
{
var container = BuildUnityContainer();
System.Web.Mvc.DependencyResolver.SetResolver(new
UnityDependencyResolver(container));
// register dependency resolver for WebAPI RC
GlobalConfiguration.Configuration.DependencyResolver = new
Unity.WebApi.UnityDependencyResolver(container);
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
// container.RegisterType<IProductServices,
ProductServices>().RegisterType<UnitOfWork>(new HierarchicalLifetimeManager());
RegisterTypes(container);
return container;
}
public static void RegisterTypes(IUnityContainer container)
{
//Component initialization via MEF
ComponentLoader.LoadContainer(container, ".bin", "WebApi.dll");
ComponentLoader.LoadContainer(container, ".bin", "BusinessServices.dll");
}
}
}
It is kind of redefining Bootstrapper class without touching our existing controller methods. We now don’t
even have to register type for ProductServices as well, we already did this in BusinessServices project.
15. Note that in RegisterTypes method we load components/dlls through reflection making use of
ComponentLoader.We wrote two lines, first to load WebAPI.dll and another one to load Business Services.dll.
Had the name of BusinessServicess.dll be WebAPI.Services.dll, then we would have only written one line of
code to load both the WebAPI and BusinessService dll like shown below,
ComponentLoader.LoadContainer(container, ".bin", "WebApi*.dll");
Yes we can make use of Regex.
Running the application
Just run the application, we get,
16. We already have our test client added, but for new readers, just go to Manage Nuget Packages, by right
clicking WebAPI project and type WebAPITestClient in searchbox in online packages,
You’ll get “A simple Test Client for ASP.NET Web API”, just add it. You’ll get a help controller in Areas->
HelpPage like shown below,
17. I have already provided the database scripts and data in my previous article, you can use the same.
Append “/help” in the application url, and you’ll get the test client,
You can test each service by clicking on it. Once you click on the service link, you'll be redirected to test the
service page of that particular service.On that page there is a button Test API in the right bottom corner, just
press that button to test your service,
20. We get in database,
Delete product:
In database:
21. Advantages of this design
In my earlier articles I focussed more on design flaws, but our current design have emerged with few added
advantages,
1. We got an extensible and loosely coupled application design that can go far with more new components
added in the same way.
2. Registering types automatically through reflection. Suppose we want to register any Interface
implementation to our REST endpoint, we just need to load that dll in our Bootstrapper class, or if dll’s are of
common suffix names then we just have to place that dll in bin folder, and that will automatically be loaded at
run time.
Image source: http://a.pragprog.com/magazines/2013-07/images/iStock_000021011143XSmall__1mfk9b__.jpg
22. 3. Database transactions or any of such module is now not exposed to the service endpoint, this makes our
service more secure and maintains the design structure too.
Conclusion
We now know how to use Unity container to resolve dependency and perform inversion of control using MEF
too.In my next article I’ll try to explain how we can open multiple endpoints to our REST service and create
custom url’s in the true REST fashion in my WebAPI. Till then Happy Coding You can also download the
source code from GitHub. Add the required packages, if they are missing in the source code.
About Author
Akhil Mittal works as a Sr. Analyst in Magic Software and have an experience of more than 8 years in C#.Net. He is a
codeproject and a c-sharpcorner MVP (Most Valuable Professional). Akhil is a B.Tech (Bachelor of Technology) in
Computer Science and holds a diploma in Information Security and Application Development from CDAC. His work
experience includes Development of Enterprise Applications using C#, .Net and Sql Server, Analysis as well as Research
and Development. His expertise is in web application development. He is a MCP (Microsoft Certified Professional) in
Web Applications (MCTS-70-528, MCTS-70-515) and .Net Framework 2.0 (MCTS-70-536).