Tuesday, August 8, 2017

Dependency Injector NINJECT full example

Here is example of library, using Ninject and also test

Library:

using Ninject;
using Ninject.Modules;

namespace NinjectExample
{
    #region Interface
    public interface IProduct
    {
        string InsertProduct();
    }
    #endregion

    #region Interface implementation
    public class ConcreteProduct1 : IProduct
    {
        public string InsertProduct()
        {
            string value = "Dependency 1 injection using Ninject";
            return value;
        }
    }

    public class ConcreteProduct2 : IProduct
    {
        public string InsertProduct()
        {
            string value = "Dependency 2 injection using Ninject";
            return value;
        }
    }
    #endregion

    #region Dependency Injector
    internal class ProductsBinder : NinjectModule
    {
        private string _productName;

        public ProductsBinder(string productName)
        {
            _productName = productName;
        }

        public override void Load()
        {
            switch (_productName)
            {
                case "DataAccessLayer1":
                    Bind<IProduct>().To<ConcreteProduct1>();
                    break;
                case "DataAccessLayer2":
                    Bind<IProduct>().To<ConcreteProduct2>();
                    break;
            }
        }
    }
    #endregion

    #region Factory
    public class FactoryProduct
    {
        public static IProduct Create(string name)
        {
            IKernel krn = new StandardKernel(new ProductsBinder(name));
            return krn.Get<IProduct>();
        }
    }
    #endregion
}

Test:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NinjectExample;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            IProduct dl = FactoryProduct.Create("DataAccessLayer1");
            Assert.AreEqual("Dependency 1 injection using Ninject", dl.InsertProduct());
        }

        [TestMethod]
        public void TestMethod2()
        {
            IProduct dl = FactoryProduct.Create("DataAccessLayer2");
            Assert.AreEqual("Dependency 2 injection using Ninject", dl.InsertProduct());
        }
    }
}

Of course, all tests passed. 

No comments:

Post a Comment