How to resolve multiple dependencies for the same interface in a constructor using Unity

QU:-How to register and use Multiple Classes Implementing Same Interface in Unity?

Qu:- How to resolve multiple dependencies for the same interface in a constructor using Unity

While discussing with one of my friend we have came across this question –  how to register and use multiple classes implementing same interface in unity. For that  reason i am writing this article, hope this will help to understand the concepts.

Here we will see this concepts can be implemented using

1) Using Generic Class  — Part I

2) Using ‘Named registration’ & ‘[Dependency]’ attribute  — Part II

Prerequisites: MVC 5 and Unity libraries

Part I :- Using Generic class

Interface:-  ITest


public interface ITest<T> where T : class
// public interface ITest
{
int MyProperty1 { get; set; }
int MyProperty2 { get; set; }
}

Class:- ClsTest


public class ClsTest : ITest<ClsTest>
{
public int _myproperty1 = 20;
public int _myproperty2 = 20;

public int MyProperty1
{
get
{
return _myproperty1;
}
set
{
_myproperty1 = value;
}
}

public int MyProperty2
{
get
{
return _myproperty2;
}
set
{
_myproperty2 = value;
}
}
}

Class:- ClsDemo


public class Clsdemo :ITest<Clsdemo>
{
public int _myproperty1 = 10;
public int _myproperty2 = 10;

public int MyProperty1
{
get
{
return _myproperty1;
}
set
{
_myproperty1 = value;
}
}

public int MyProperty2
{
get
{
return _myproperty2;
}
set
{
_myproperty2 = value;
}
}

}

Register unity in Global.asax file:-


public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();

//Register Unity
UnityConfig.RegisterComponents();

FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}

Unity Class:-  UnityConfig


public static class UnityConfig
{
public static void RegisterComponents()
{
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<ITest, ClsTest>();
container.RegisterType<ITest, Clsdemo>();

DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}

Controller :-TestController


public class TestController : Controller
{

//ITest iTobj;
ITest<ClsTest> iTobj;
ITest<Clsdemo> iTobj1;

// public TestController(ITest iT)
//public TestController(ITest<ClsTest> iT)
public TestController(ITest<ClsTest> iT, ITest<Clsdemo> Obj1)
{
iTobj = iT;
iTobj1 = Obj1;

}
//
// GET: /Test/
public ActionResult Index()
{
return View();
}

}

Controller:- HomeController


public class HomeController : Controller
{
ITest<Clsdemo> obj1;
// ITest obj1;

//public HomeController(ITest<Clsdemo> Obj1)
public HomeController(ITest Obj1)
{

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

}

After running the above code you will able to get the class object as per the controller classes.

Note:- If you used MVC4 and added mvc4.unity from Nu-get package you will get Bootstraper.cs class file. In my case i am using MVC5 so after adding unity library i am getting  UnityConfig.cs class in App_start folder but both the unity class have the same implementation.

————————————————————————————————————————–

Part II  — Using ‘Named registration’ & ‘[Dependency]’ attribute 

UnityConfig.cs:


// "<strong>NormalAccount"</strong> is assigned as a name for RegisterType

container.RegisterType<IAccountService, AccountService>("NormalAccount");

// "<strong>SpecialAccount"</strong> is assigned as a name for RegisterType

container.RegisterType<IAccountService, SplAccountService>("SpecialAccount");

AccountInfoController.cs:


private IAccountService normalAcc;
private IAccountService specialAcc;

//  Dependency attribute is used with Named RegisterType as per requirement.

public SplAccountInfoController([Dependency("NormalAccount")]IAccountService accountService1, [Dependency("SpecialAccount")]IAccountService accountService2)
{
this.normalAcc = accountService1;
this.specialAcc = accountService2;
}

 

 

Multi-Select List/Drop Down in Asp.Net MVC4

This article is basically focused on how we can use Multi-Select List/ Drop Down using Asp.Net MVC4 and Bootstrap.

Basic steps for selecting multiple values from Multi-Select List/Drop Down List using Asp.Net MVC and Bootstrap.

Step 1:- Create the model class with name as MoviesModel

public class MoviesModel
{
// This will hold the selected values in List/Drop Down Box 
public string[] SelectMovies { get; set; }
Public IEnumerable AllMovies { get; set; }
}

Step 2:- Create new controller with name as MoviesController

public class MoviesController : Controller
{
   // GET: /Movies
         public ActionResult Index()
         {
               MoviesModel movmod=new MoviesModel();
               movmod.SelectMovies= new string[] { "1","2" };
               movmod.AllMovies = GetAllMovies();
               return View(movmod);
         }

         private IEnumerable<SelectListItem> GetAllMovies()
        {
            List<SelectListItem> allmov = new List<SelectListItem>();
            allmov.Add(new SelectListItem { Value = "1", Text = "Terminator" });
            allmov.Add(new SelectListItem { Value = "2", Text = "Harry Potter" });
            allmov.Add(new SelectListItem { Value = "3", Text = "Matrix" });
            allmov.Add(new SelectListItem { Value = "4", Text = "Fast and Furious" });
            allmov.Add(new SelectListItem { Value = "5", Text = "Tokyo Drift" });
            allmov.Add(new SelectListItem { Value = "6", Text = "Spider Man" });
            allmov.Add(new SelectListItem { Value = "7", Text = "Men In Black" });
            return allmov.AsEnumerable();
        }
      
  // POST: /Movies
         [HttpPost]
        public ActionResult Index(MoviesModel movmodel)
        {            
               movmodel.AllMovies = GetAllMovies();
               return View(movmodel);
        }

}

Step 3:- Create new view with name as Index


     @{
         ViewBag.Title = "Index";
      }

      <h2>Example of Multiselect List/ Drop down in Asp.Net MVC4</h2>

      @model MvcAssign.Models.MoviesModel

      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
      <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"   rel="stylesheet" type="text/css" />
      <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
      <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
      <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>

        @using (Html.BeginForm())
        { 
             <div class="form-group">
              <label class="col-lg-2 control-label" for="movies">Movies:</label>
               <div class="col-lg-10">
                @Html.ListBoxFor((m => m.SelectMovies), new SelectList(Model.AllMovies, "Value", "Text", Model.SelectMovies), new { @class = "multiselect", multiple = "multiple", id = "lstMovies" })
            
                 @*@Html.DropDownListFor((m => m.SelectMovies), new SelectList(Model.AllMovies, "Value", "Text", Model.SelectMovies), new { @class = "multiselect", multiple = "multiple", id = "lstFruits",allowmultiple=true })*@

                </div>
             </div>
             <br />    
             <input type="submit" value="Submit" style="margin-left:48px;" />
        }


   <script type="text/javascript">
        $(function () {
          $('[id*=lstMovies]').multiselect({
              includeSelectAllOption: true                
               });
           });
    </script>

 

After running the above code you will get the following output

MultiSelectDropDown_1

MultiSelectDropDown_2

After Http Post(i.e on button click) we will get the selected item in List/Drop Down box as shown below.

MultiSelectDropDown_3

In the next article we will see the filtering and List/Drop Down box value through JQuery.

Reference for Multi-Select Bootstrap js
http://davidstutz.github.io/bootstrap-multiselect/

🙂 Happy Coding…