Sunday, 4 February 2018

How to resolve dependency of an interface on multiple concrete classes?

Create interface-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DIOperations
{
    public class Person
    {
        public string name { get; set; }
        public int age { get; set; }
    }
    public interface IPerson
    {
        Person GetPerson();
    }
}
Implement interface on concrete classes-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DIOperations
{
    public class Male : IPerson
    {
        public Person GetPerson()
        {
            return new Person() { name = "Rami", age = 25 };
        }
        // Some other Male Specific Properties and Methods
    }
    public class Female : IPerson
    {
        public Person GetPerson()
        {
            return new Person() { name = "Jash", age = 21 };
        }
        // Some other Male Specific Properties and Methods
    }
}
Register dependency by using Unity-

Then open Bootstrapper.cs and add the following registrations to BuildUnityContainer() method –
container.RegisterType<IPerson, Male>("Male");
container.RegisterType<IPerson, Female>("Female");
Inject dependency at run time-

using DIOperations;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DIWeb.Controllers
{
    public class HomeController : Controller
    {
        private IPerson malePerson;
        private IPerson femalePerson;

        public HomeController([Dependency("Male")]IPerson malePerson, [Dependency("Female")]IPerson femalePerson)
        {
            this.malePerson = malePerson;
            this.femalePerson = femalePerson;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Male()
        {
            return View(malePerson.GetPerson());
        }

        public ActionResult Female()
        {
            return View(femalePerson.GetPerson());
        }
    }
}

No comments:

Post a Comment