April 26, 2016 by Christoff Truter C# PostSharp Ninject
Dependency injection is one of the common approaches when dealing with the inversion of control (IoC) design principle and the dependency inversion principle (DIP).
Basically instead of passing to / instantiating in, a concrete object, we rely on abstractions (e.g. an interface).
This loosens the coupling between classes, making our code more readable, reusable, testable, maintainable and allows concurrent / independent development of source code.
I am not going to go into too much detail about its various advantages, this post is more interested in its practical implementation.
Observe the following snippet.
class Products { private IProductRepository _productRepository; public Products(IProductRepository productRepository) { _productRepository = productRepository; } public void SomeMethod() { _productRepository.GetAll(); } }
var kernel = new StandardKernel(); kernel.Bind<IProductRepository>().To<ProductRepository>(); var products = kernel.Get<Products>(); products.SomeMethod();
class Products { [Dependency] private IProductRepository _productRepository = null; public void SomeMethod() { _productRepository.GetAll(); } }
static class Dependencies { static StandardKernel _kernel { get; } = new StandardKernel(); static Dependencies() { _kernel.Bind<IProductRepository>().To<ProductRepository>(); } public static object Get(Type type, params IParameter[] parameters) => _kernel.Get(type, parameters); public static object Get<T>(params IParameter[] parameters) => _kernel.Get<T>(parameters); }
[Serializable] class DependencyAttribute : LocationInterceptionAspect { public override void OnGetValue(LocationInterceptionArgs args) { args.Value = args.GetCurrentValue(); if (args.Value == null) { args.Value = Dependencies.Get(args.Location.LocationType); args.ProceedSetValue(); } } }
class ProductRepository : IProductRepository { [Dummy] public List<Product> GetAll() { return new List<Product> { new Product { Name = "Motorized Ice Cream Cone" }, new Product { Name = "Self-Stirring Mug" }, new Product { Name = "Battery-Powered Scissors" } }; } }
class DummyAttribute : MethodLevelAspect { public override void CompileTimeInitialize(MethodBase method, AspectInfo aspectInfo) { #if !DEBUG throw new NotImplementedException($"{method.Name}, {method.ReflectedType}"); #endif } }
Well, I am off to Calitzdorp with my girlfriend for some R&R, let me know in the comment section what you think (about the post that is )
Thanks for the learning! August 18, 2016 by Mr Min
Awesome post thanks!