1

I want to load my class dynamically by using the Unity DI container based on country code saved in variable.

Our win apps has a shipping functionality for which we use web service developed by 3rd party company like UPS, FedEx and Purolator.

Now how should I design my code with unity, so that I could load my shipping class based on country code stored in variable?

Suppose this is my sample or proposed class design:

   public interface IShip
    {
        string Ship();
    }

    public class UPS : IShip
    {
        public string Ship()
        {
        }
    }

    public class FedEX : IShip
    {
        public string Ship()
        {
        }

    }

    public class Purolator : IShip
    {
        public string Ship()
        {
        }

    }

How can I use unity to load class based on variable value.

What if GB is stored in variable and I want to load UPS class and invoke ship function ?

Suppose FR is stored in a variable and I want to load UPS class and invoke ship function ?

Suppose if US is stored in variable and I want to load FedEx class and invoke ship function ?

Suppose CA is stored in variable and I want to load Purolator class and invoke ship function ?

Icepickle
  • 12,689
  • 3
  • 34
  • 48
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • Can you show the consuming code of IShip? – Yacoub Massad Mar 21 '16 at 18:36
  • the class design from my thought. code not started. i like to know how to use unity DI which load class dynamically based on country code supplied at run time. – Thomas Mar 21 '16 at 19:07
  • Use Named registration of multiple implementation with interface. Similar [answer here](http://stackoverflow.com/a/23669951/881798). – vendettamit Mar 21 '16 at 21:00

1 Answers1

2

You can register your classes by name, and resolve them depending on your condition:

container.RegisterType<IShip, UPS>("UPS");
container.RegisterType<IShip, FedEX>("FedEX");
container.RegisterType<IShip, Purolator>("Purolator");

public IShip GetShippment(string c)
{

    if (c == "GB" || c == "FR")
        return container.Resolve<IShip>("UPS");

    if (c == "US")
        return container.Resolve<IShip>("FedEX");

    if (c == "CA")
        return container.Resolve<IShip>("Purolator");

    throw new NotImplementedException();
}
...
var shippment = GetShippment("CA");
shippment.Ship();
Backs
  • 24,430
  • 5
  • 58
  • 85