Unity (MVC Example)
“The Unity Container (Unity) is a lightweight, extensible dependency injection container. It facilitates building loosely coupled applications”
This was very simple to setup for an ASP.NET MVC project (net461) using the nuget packages:
- Unity.Container, Version=5.7.0
- Unity.Abstractions, Version=3.3.0
- Unity.Mvc, Version=5.0.13
Implementation is as simple as this:
1 | ~ /App_Start/UnityConfig.cs |
Modules
If you have worked with amazing Dependency Injection Frameworks such as Autofac or Ninject you would expect to be able to create cohesive modules right? Well Unity doesn’t support this out of the box however you can create extension methods that do pretty much the same thing, just remember the order will matter if you are going to be calling container.Resolve
later down the stack.
Simply call container.AddExtension
and new up the module:
1 | ~ /App_Start/UnityConfig.cs |
The module then inherits the Container
from the base class UnityContainerExtension
1 | using Unity; |
Abstract Factory
Unity is unable to automatically resolve IEnumerable<T>
dependencies which you could use with an Abstract Factory.
You can however get around this by naming the dependency.
1 | Container.RegisterType<IPriceRule, EachPriceRule>("EachPriceRule"); |
This is then automagically injected into the consumer.
1 | public class FooController : Controller |
References
- https://www.codeproject.com/Articles/988257/Dependency-Injection-using-Unity-container
- https://msdn.microsoft.com/en-us/library/dn223671(v=pandp.30).aspx
- https://github.com/unitycontainer/unity
- https://github.com/unitycontainer/aspnet-mvc
- https://www.c-sharpcorner.com/article/dependency-injection-in-asp-net-mvc-5/