I need help from you guys. Currently I am working on Dependency Injection in my Console Application. In single class i have define three layers just to understand dependency injection. Actually I am trying to inject object of data acess layer which can be either Oracle or Sql based on the requirement.But injection is happening based on which layer is registerd last.Could any guys tell me how can I do proper injection?
UI LAYER:
class Program
{
static void Main(string[] args)
{
IUnityContainer objconatiner = new UnityContainer();
objconatiner.RegisterType<Customer>();
objconatiner.RegisterType<IDal, SqlserverDal>();
objconatiner.RegisterType<IDal, OracleServerDal>();
Customer ocust = objconatiner.Resolve<Customer>();
ocust.CustName = "Taylor Swift";
ocust.Add();
}
}
MIDDLE LAYER:
public class Customer
{
private IDal oidal;
public string CustName { get; set; }
public Customer(IDal idal)
{
oidal = idal;
}
public void Add()
{
oidal.Add();
}
}
DAL LAYER:
public interface IDal
{
void Add();
}
public class SqlserverDal : IDal
{
public void Add()
{
Console.Write("Now using Sql server");
}
}
public class OracleServerDal : IDal
{
public void Add()
{
Console.Write("Now using Orcale server");
}
}
This exact situation is where named registrations come in to play.
static void Main(string[] args)
{
IUnityContainer objconatiner = new UnityContainer();
objconatiner.RegisterType<Customer>();
objconatiner.RegisterType<IDal, SqlserverDal>("SqlServer");
objconatiner.RegisterType<IDal, OracleServerDal>("Oracle");
Customer ocust = objconatiner.Resolve<Customer>();
ocust.CustName = "Taylor Swift";
ocust.Add();
}
public class Customer
{
private IDal oidal;
public string CustName { get; set; }
public Customer([Dependency("SqlServer")]IDal idal)
{
oidal = idal;
}
public void Add()
{
oidal.Add();
}
}
Now both registrations can be used but you must specify which registration you want via name when you do your resolving, this can be done via attributes as I have shown above or via the Resolve
call that takes in a string.